Python 列表理解,但在根据条件选择迭代的列表上
我有两个列表,分别是Python 列表理解,但在根据条件选择迭代的列表上,python,list,list-comprehension,Python,List,List Comprehension,我有两个列表,分别是list1和list2: list1 = [4, 3, 20, 10] list2 = ['a', 'f', 'd', 'b'] 我想创建一个新的列表result,条件是如果我的条件num==10为True,那么result应该保存list1中的内容,否则它应该保存list2中的内容。下面是我尝试的代码: num = 10 result = [element for element in list1 if num == 10 else list2] 但这会引起语法错误。我
list1
和list2
:
list1 = [4, 3, 20, 10]
list2 = ['a', 'f', 'd', 'b']
我想创建一个新的列表result
,条件是如果我的条件num==10
为True
,那么result
应该保存list1
中的内容,否则它应该保存list2
中的内容。下面是我尝试的代码:
num = 10
result = [element for element in list1 if num == 10 else list2]
但这会引起语法错误。我应该如何做到这一点
上述代码的预期输出为:
[4, 3, 20, 10] # stored in `result`
您只是缺少一些括号:
result = [element for element in (list1 if num == 10 else list2)]
列表理解可以具有如下过滤条件(comp\u if
in):
[a for a in b if c]
在当前版本中,list1
是b
,num==10
是c
,但您的附加else列表2在语法上无效
您需要明确指出,您的条件表达式都是b
的一部分,您可以使用括号来实现这一点 如果您只想根据您的条件创建一个新的列表结果
,您只需执行以下操作(无需理解列表):
上述结果基于这样一个事实:Python将布尔值True
和False
分别视为1
和0
。因此,我们根据条件从元组中获取所需的列表
执行相同任务的其他备选方案:
# Alternative 1: Using your `if`/`else` logic
result = (list1 if num == 10 else list2)
# Alternative 2: using `and`/`or` logic
result = (num == 10 and list1) or list2
如果您必须使用列表理解(可能是对元素执行某些操作),则您可以将列表理解与上述任何条件一起使用,如下所示:
>>> num = 10
>>> list1 = [4, 3, 20, 10]
>>> list2 = ['a', 'f', 'd', 'b']
# Using tuple of lists with boolean index
>>> result = [element for element in (list2, list1)[num==10]]
>>> result
[4, 3, 20, 10]
# Using `if`/`else` logic
>>> result = [element for element in (list1 if num == 10 else list2)]
>>> result
[4, 3, 20, 10]
# Using using `and`/`or` logic
>>> result = [element for element in (num == 10 and list1) or list2]
>>> result
[4, 3, 20, 10]
就这样。谢谢lot@Maryam不用担心,注意
>>> num = 10
>>> list1 = [4, 3, 20, 10]
>>> list2 = ['a', 'f', 'd', 'b']
# Using tuple of lists with boolean index
>>> result = [element for element in (list2, list1)[num==10]]
>>> result
[4, 3, 20, 10]
# Using `if`/`else` logic
>>> result = [element for element in (list1 if num == 10 else list2)]
>>> result
[4, 3, 20, 10]
# Using using `and`/`or` logic
>>> result = [element for element in (num == 10 and list1) or list2]
>>> result
[4, 3, 20, 10]