python - 在 Python 中查找 2 个列表中相同元素的数量

标签 python arrays array-intersect

如果我有 2 个列表,在 Python 中说:

l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']

有没有办法找出它们有多少相同的元素。在这种情况下,它将是 2(c 和 d)

我知道我可以做一个嵌套循环,但是没有像 php 中那样带有 array_intersect 函数的内置函数吗

谢谢

最佳答案

您可以为此使用集合交集:)

l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
set(l1).intersection(l2)
set(['c', 'd'])

关于python - 在 Python 中查找 2 个列表中相同元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2500124/

相关文章:

python - Annotation auto-placement (matploylib.pyplot) - 或列表注释

java - 一次读入文本文件 1 行并将单词拆分为 Array Java

C++数组访问

php - 使用来自另一个二维关联数组的多个级别的键过滤二维关联数组

PHP Array_intersect 在具有未知键数的多维数组上

Python 异步 : unreferenced tasks are destroyed by garbage collector?

Python - 如何在 "if x in range"语句中使用 float

python - 无法在 OSX 上成功执行 ipython 笔记本命令

java - 如何从排序数组中删除重复元素

php - 如何在 php 中获取重复的多维数组