找到两个嵌套列表的交集?
- 2024-12-18 08:39:00
- admin 原创
- 138
问题描述:
我知道如何获取两个平面列表的交集:
b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
或者
def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
但是当我必须找到嵌套列表的交集时,我的问题就开始了:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
最后我想得到:
c3 = [[13,32],[7,13,28],[1,6]]
你们能帮我一下吗?
有关的
在 python 中展平浅列表
解决方案 1:
您不需要定义交集。它已经是集合的一等部分。
>>> b1 = [1,2,3,4,5,9,11,15]
>>> b2 = [4,5,6,7,8]
>>> set(b1).intersection(b2)
set([4, 5])
解决方案 2:
如果你想:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [[13, 32], [7, 13, 28], [1,6]]
那么这是针对 Python 2 的解决方案:
c3 = [filter(lambda x: x in c1, sublist) for sublist in c2]
在 Python 3 中filter
返回一个可迭代对象而不是list
,因此您需要使用filter
以下方式包装调用list()
:
c3 = [list(filter(lambda x: x in c1, sublist)) for sublist in c2]
解释:
过滤器部分获取每个子列表的项目并检查它是否在源列表 c1 中。对 c2 中的每个子列表执行列表推导。
解决方案 3:
对于只想找到两个列表交集的人,Asker 提供了两种方法:
b1 = [1,2,3,4,5,9,11,15] b2 = [4,5,6,7,8] b3 = [val for val in b1 if val in b2]
和
def intersect(a, b): return list(set(a) & set(b)) print intersect(b1, b2)
但是有一种更有效的混合方法,因为您只需要在列表/集合之间进行一次转换,而不是三次:
b1 = [1,2,3,4,5]
b2 = [3,4,5,6]
s2 = set(b2)
b3 = [val for val in b1 if val in s2]
这将在 O(n) 中运行,而他原来的涉及列表理解的方法将在 O(n^2) 中运行
解决方案 4:
功能方法:
input_list = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]
result = reduce(set.intersection, map(set, input_list))
它可以应用于更一般的 1+ 列表的情况
解决方案 5:
纯列表理解版本
>>> c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
>>> c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
>>> c1set = frozenset(c1)
扁平变体:
>>> [n for lst in c2 for n in lst if n in c1set]
[13, 32, 7, 13, 28, 1, 6]
嵌套变体:
>>> [[n for n in lst if n in c1set] for lst in c2]
[[13, 32], [7, 13, 28], [1, 6]]
解决方案 6:
& 运算符取两个集合的交集。
{1, 2, 3} & {2, 3, 4}
Out[1]: {2, 3}
解决方案 7:
取两个列表交集的 Python 方式是:
[x for x in list1 if x in list2]
解决方案 8:
您应该使用此代码(取自http://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks)进行展平,该代码未经测试,但我很确定它可以工作:
def flatten(x):
"""flatten(sequence) -> list
Returns a single, flat list which contains all elements retrieved
from the sequence and all recursively contained sub-sequences
(iterables).
Examples:
>>> [1, 2, [3,4], (5,6)]
[1, 2, [3, 4], (5, 6)]
>>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
[1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""
result = []
for el in x:
#if isinstance(el, (list, tuple)):
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
展平列表后,可以按通常的方式执行交集:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
def intersect(a, b):
return list(set(a) & set(b))
print intersect(flatten(c1), flatten(c2))
解决方案 9:
由于intersect
已经定义,所以基本的列表理解就足够了:
>>> c3 = [intersect(c1, i) for i in c2]
>>> c3
[[32, 13], [28, 13, 7], [1, 6]]
感谢 S. Lott 的评论和 TM. 的相关评论,因此有所改进:
>>> c3 = [list(set(c1).intersection(i)) for i in c2]
>>> c3
[[32, 13], [28, 13, 7], [1, 6]]
解决方案 10:
鉴于:
> c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
> c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
我发现如果使用集合操作,下面的代码会运行良好,并且可能更简洁:
> c3 = [list(set(f)&set(c1)) for f in c2]
它得到了:
> [[32, 13], [28, 13, 7], [1, 6]]
如需订购:
> c3 = [sorted(list(set(f)&set(c1))) for f in c2]
我们得到:
> [[13, 32], [7, 13, 28], [1, 6]]
顺便说一句,为了更具 Python 风格,这个也很好:
> c3 = [ [i for i in set(f) if i in c1] for f in c2]
解决方案 11:
您是否考虑过[1,2]
与 相交[1, [2]]
?也就是说,您只关心数字,还是也关心列表结构?
如果只有数字,请研究如何“展平”列表,然后使用该set()
方法。
解决方案 12:
我不知道我回答你的问题是否晚了。读完你的问题后,我想出了一个可以同时处理列表和嵌套列表的函数 intersect()。我使用递归来定义这个函数,它非常直观。希望这就是你要找的:
def intersect(a, b):
result=[]
for i in b:
if isinstance(i,list):
result.append(intersect(a,i))
else:
if i in a:
result.append(i)
return result
例子:
>>> c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
>>> c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
>>> print intersect(c1,c2)
[[13, 32], [7, 13, 28], [1, 6]]
>>> b1 = [1,2,3,4,5,9,11,15]
>>> b2 = [4,5,6,7,8]
>>> print intersect(b1,b2)
[4, 5]
解决方案 13:
我也在寻找方法,最终结果是这样的:
def compareLists(a,b):
removed = [x for x in a if x not in b]
added = [x for x in b if x not in a]
overlap = [x for x in a if x in b]
return [removed,added,overlap]
解决方案 14:
要定义正确考虑元素基数的交集,请使用Counter
:
from collections import Counter
>>> c1 = [1, 2, 2, 3, 4, 4, 4]
>>> c2 = [1, 2, 4, 4, 4, 4, 5]
>>> list((Counter(c1) & Counter(c2)).elements())
[1, 2, 4, 4, 4]
解决方案 15:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [list(set(c2[i]).intersection(set(c1))) for i in xrange(len(c2))]
c3
->[[32, 13], [28, 13, 7], [1, 6]]
解决方案 16:
我们可以使用 set 方法来实现这一点:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
result = []
for li in c2:
res = set(li) & set(c1)
result.append(list(res))
print result
解决方案 17:
# Problem: Given c1 and c2:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
# how do you get c3 to be [[13, 32], [7, 13, 28], [1, 6]] ?
c3
以下是不涉及集合的设置方法之一:
c3 = []
for sublist in c2:
c3.append([val for val in c1 if val in sublist])
但如果你只想使用一行,你可以这样做:
c3 = [[val for val in c1 if val in sublist] for sublist in c2]
它是列表推导内的列表推导,这有点不寻常,但我认为你应该不会有太多困难去理解它。
解决方案 18:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [list(set(i) & set(c1)) for i in c2]
c3
[[32, 13], [28, 13, 7], [1, 6]]
对我来说,这是一种非常优雅且快捷的方法:)
解决方案 19:
平面列表可以轻松制作reduce
。
您只需使用初始化程序——reduce
函数中的第三个参数。
reduce(
lambda result, _list: result.append(
list(set(_list)&set(c1))
) or result,
c2,
[])
上述代码适用于 python2 和 python3,但您需要导入 reduce 模块from functools import reduce
。有关详细信息,请参阅以下链接。
对于python2
对于python3
解决方案 20:
查找可迭代对象之间的差异和交集的简单方法
如果重复很重要,请使用此方法
from collections import Counter
def intersection(a, b):
"""
Find the intersection of two iterables
>>> intersection((1,2,3), (2,3,4))
(2, 3)
>>> intersection((1,2,3,3), (2,3,3,4))
(2, 3, 3)
>>> intersection((1,2,3,3), (2,3,4,4))
(2, 3)
>>> intersection((1,2,3,3), (2,3,4,4))
(2, 3)
"""
return tuple(n for n, count in (Counter(a) & Counter(b)).items() for _ in range(count))
def difference(a, b):
"""
Find the symmetric difference of two iterables
>>> difference((1,2,3), (2,3,4))
(1, 4)
>>> difference((1,2,3,3), (2,3,4))
(1, 3, 4)
>>> difference((1,2,3,3), (2,3,4,4))
(1, 3, 4, 4)
"""
diff = lambda x, y: tuple(n for n, count in (Counter(x) - Counter(y)).items() for _ in range(count))
return diff(a, b) + diff(b, a)
解决方案 21:
from random import *
a = sample(range(0, 1000), 100)
b = sample(range(0, 1000), 100)
print(a)
print(b)
print(set(a).intersection(set(b)))