Joh*_*ohn 5 python arrays array-intersect
在Python中如果我有2个列表说:
l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
Run Code Online (Sandbox Code Playgroud)
有没有办法找出他们有多少元素相同.在这种情况下它将是2(c和d)
我知道我可以做一个嵌套循环但是没有内置函数,就像php中的array_intersect函数一样
谢谢
Wol*_*lph 10
你可以使用集合交集:)
l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
set(l1).intersection(l2)
set(['c', 'd'])
Run Code Online (Sandbox Code Playgroud)
>>> l1 = ['a', 'b', 'c', 'd']
>>> l2 = ['c', 'd', 'e']
>>> set(l1) & set(l2)
set(['c', 'd'])
Run Code Online (Sandbox Code Playgroud)
如果您只有唯一元素,则可以使用set数据类型并使用intersection:
s1, s2 = set(l1), set(l2)
num = len(s1.intersection(s2))
Run Code Online (Sandbox Code Playgroud)