Python列表理解:有没有办法在list1或list2中为x执行[func(x)]

时间:2014-07-24 01:02:14

标签: python list-comprehension

或者[list1和list2中的x的[func(x)](对于某些函数func),而不必创建恰好是两个列表的并集或交集的新列表。

3 个答案:

答案 0 :(得分:2)

您可以使用itertools.chain加入这两个列表,而无需创建新列表:

from itertools import chain
lst = [x for x in chain(list1, list2)]

以下是演示:

>>> from itertools import chain
>>> list1 = [1, 2, 3]
>>> list2 = [4, 5, 6]
>>> [x for x in chain(list1, list2)]
[1, 2, 3, 4, 5, 6]
>>> list(chain(list1, list2))  # Equivalent
[1, 2, 3, 4, 5, 6]
>>>

答案 1 :(得分:2)

import itertools

[x for x in itertools.chain(list1,list2)]

请注意,这将添加重复项,因此它既不是联合也不是交集。如果你想要一个真正的联合/交集:

set.union(map(set, [list1,list2])) # cast to list if you need
# union
set.intersection(map(set, [list1,list2])) # cast to list if you need
# intersection

从你的编辑:

def func(x):
    pass
    # do something useful

for element in list1:
    if element in list2:
        func(element)
# Or, but less readably imo
# # for element in filter(lambda x: x in list2, list1):
# #     func(element)

答案 2 :(得分:1)

你想要itertools.chain()

[... in itertools.chain(list1, list2)]