简体   繁体   English

Python列表初始化中的条件术语

[英]Conditional terms in Python list initialization

I want to do something like this: 我想做这样的事情:

a = some_funct()
b = [ 1, a if a is not None ]

The list b should be one element long if a is None, and two elements long if a is not None. 如果a为None,则列表b应该是一个元素,如果a不是None,则列表b应该是两个元素。 Is this possible in Python or do I have to use a separate if check followed by add()? 这是可能的Python或我必须使用单独的if检查后跟add()?

Doesn't look the best, but you could do 看起来不是最好,但你可以做到

b = [1] + ([a] if a is not None else [])

Of course, it would be better to check as it increases code readability. 当然,最好检查一下,因为它增加了代码的可读性。

a = some_funct()
b = [ 1, a ] if a is not None else [1]

You can do this using list comprehension 您可以使用列表理解来完成此操作

b = [x for x in (1, a) if x is not None]

The tuple (1, a) is the total set, b will become a list of all elements in that total set which are not None 元组(1, a)是总集合,b将成为该集合中所有元素的列表,而不是None

我太末到本场比赛,但我有同样的问题,看到其他的答案后,我想出了使用此解决方案sets

list({1, a or 1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM