列表理解,但在基于条件选择迭代的列表上

时间:2018-02-24 09:22:25

标签: python list list-comprehension

我有两个列表list1list2

list1 = [4, 3, 20, 10]
list2 = ['a', 'f', 'd', 'b']

我想基于以下条件创建新列表result:如果我的条件num==10True,则result应保留{{1}的内容其他它应该保留list1的内容。以下是我尝试的代码:

list2

但这是在提高num = 10 result = [element for element in list1 if num == 10 else list2] 。我该怎么做到这一点?

上述代码的预期输出为:

SyntaxError

2 个答案:

答案 0 :(得分:5)

你只是遗漏了一些括号:

result = [element for element in (list1 if num == 10 else list2)]

列表理解可以具有过滤条件(the language reference中的comp_if),如下所示:

[a for a in b if c]

在您当前的版本中,list1bnum == 10c,但您的附加else list2在语法上无效。

您需要明确指出您的条件表达式是b的所有部分,您可以使用括号。

答案 1 :(得分:3)

如果您只想根据条件result创建新列表num==10,则可以执行(无需列表理解)

>>> result = (list2, list1)[num==10]
>>> result
[4, 3, 20, 10]

以上结果基于Python将布尔值TrueFalse分别视为10这一事实。因此,我们根据条件从元组中获取所需的列表。

其他替代方案执行相同的任务:

# 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

如果列表理解必须为您使用(可能是对元素执行某些操作),那么您可以使用 list comprehension 与上述任何条件为:

>>> 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]
相关问题