Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
以不同的条件加入python中的列表_Python_List Comprehension - Fatal编程技术网

以不同的条件加入python中的列表

以不同的条件加入python中的列表,python,list-comprehension,Python,List Comprehension,我想使用条件语句加入列表,例如: str = "\n".join["a" if some_var is True, "b", "c", "d" if other_var==1, "e"] 每个元素都有一个不同的条件子句(如果有的话),因此在这种情况下,正常的列表理解是不合适的 我想到的解决办法是: lst = ["a" if some_var is True else None, "b", "c", "d" if other_var==1 else None, "e"] str = "\n".

我想使用条件语句加入列表,例如:

str = "\n".join["a" if some_var is True, "b", "c", "d" if other_var==1, "e"]
每个元素都有一个不同的条件子句(如果有的话),因此在这种情况下,正常的列表理解是不合适的

我想到的解决办法是:

lst = ["a" if some_var is True else None, "b", "c", "d" if other_var==1 else None, "e"]
str = "\n".join[item for item in lst if item is not None]
如果有更优雅的pythonic解决方案

谢谢

梅尔


更多说明: 在上面的示例中,如果某个_var等于True,而另一个_var等于1,我希望得到以下字符串:

a
b
c
d
e
b
c
d
e
a
b
c
e
如果某个_var为False,而另一个_var等于1,我希望得到以下字符串:

a
b
c
d
e
b
c
d
e
a
b
c
e
如果某个_var为True,而另一个_var不等于1,我希望得到以下字符串:

a
b
c
d
e
b
c
d
e
a
b
c
e

我想这就是你想要的:

lst=[]
if some_var == True:
    lst.append('a')
lst.append('b')
lst.append('c')
if other_var == 1:
    lst.append('d')
lst.append('e')

如果每个元素只有在满足条件时才应添加到列表中,请分别说明每个条件,并在满足条件时添加元素。列表理解是指当您拥有一个现有列表,并且希望以某种方式处理其中的元素时

lst = []
if some_var is True:
    lst.append('a')
lst.extend(['b', 'c'])
if other_var == 1:
    lst.append('d')
lst.append('e')

这对你有用吗

items = ['a', 'b', 'c'] if cond1 else ['b', 'c']
items.extend(['d', 'e'] if cond2 else ['e'])
str = '\n'.join(items)