Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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_Python 2.7 - Fatal编程技术网

如何获取两个列表的公共元素,这两个列表本身就是python中的列表

如何获取两个列表的公共元素,这两个列表本身就是python中的列表,python,python-2.7,Python,Python 2.7,我有两份清单: l1 = [[3,1],[1,2],[1,'a'],[1,4]] l2 = [[3,1],[1,4],[1,5],[1,'a']] 我想得到它们的交点,即,[[3,1],[1,4],[1,a']。我该怎么做 l1 = [[3,1],[1,2],[1,'a'],[1,4]] l2 = [[3,1],[1,4],[1,5],[1,'a']] intersection = [] for x in l1: if x in l2: intersection.app

我有两份清单:

l1 = [[3,1],[1,2],[1,'a'],[1,4]]
l2 = [[3,1],[1,4],[1,5],[1,'a']]
我想得到它们的交点,即,
[[3,1],[1,4],[1,a']
。我该怎么做

l1 = [[3,1],[1,2],[1,'a'],[1,4]]
l2 = [[3,1],[1,4],[1,5],[1,'a']]
intersection = []
for x in l1:
    if x in l2:
        intersection.append(x)
print (intersection)
使用for循环查找相同的元素并将它们附加到另一个列表中

产出

[[3, 1], [1, 'a'], [1, 4]]
>>> 
或更短的方式,使用列表理解

l1 = [[3,1],[1,2],[1,'a'],[1,4]]
l2 = [[3,1],[1,4],[1,5],[1,'a']]

print ([x for x in l1 if x in l2])
使用for循环查找相同的元素并将它们附加到另一个列表中

产出

[[3, 1], [1, 'a'], [1, 4]]
>>> 
或更短的方式,使用列表理解

l1 = [[3,1],[1,2],[1,'a'],[1,4]]
l2 = [[3,1],[1,4],[1,5],[1,'a']]

print ([x for x in l1 if x in l2])

假设内部元素始终处于相同的顺序

out = set(map(tuple, l1)).intersection(map(tuple, l2))
输出 请注意,上面返回的是一组元组,而不是列表。但如果需要,您可以轻松地将它们转换回列表:

map(list, out)

假设内部元素始终处于相同的顺序

out = set(map(tuple, l1)).intersection(map(tuple, l2))
输出 请注意,上面返回的是一组元组,而不是列表。但如果需要,您可以轻松地将它们转换回列表:

map(list, out)

考虑到您对问题的澄清意见,请这样做:

将其中一个列表转换为一个集合(对于O(1)查找时间),然后使用列表理解

>>> l2_s = set(map(tuple, l2))
>>> [x for x in l1 if tuple(x) in l2_s]
[[3, 1], [1, 'a'], [1, 4]]

考虑到您对问题的澄清意见,请这样做:

将其中一个列表转换为一个集合(对于O(1)查找时间),然后使用列表理解

>>> l2_s = set(map(tuple, l2))
>>> [x for x in l1 if tuple(x) in l2_s]
[[3, 1], [1, 'a'], [1, 4]]

应该保留重复项吗?@timgeb如果您指的是每个子列表中元素的顺序,则是。@gill-no,但无论如何不应该有任何重复项。应该保留重复项吗?@timgeb如果您指的是每个子列表中元素的顺序,则是。@gill-no,但无论如何都不应该有任何重复项。如果列表可以包含重复项,并且结果的顺序无关紧要,这是一个很好的答案,可能对谷歌搜索这个问题的人有所帮助。如果列表可以包含重复项,并且结果的顺序无关紧要,并且可能对任何人都有帮助,这是一个很好的答案谁用谷歌搜索这个问题。