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

发布于 2024-08-25 19:49:00 字数 222 浏览 3 评论 0原文

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

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

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

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

谢谢

In Python if I have 2 lists say:

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

is there a way to find out how many elements they have the same. In the case about it would be 2 (c and d)

I know I could just do a nested loop but is there not a built in function like in php with the array_intersect function

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

何处潇湘 2024-09-01 19:49:00

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

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

You can use a set intersection for that :)

l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
set(l1).intersection(l2)
set(['c', 'd'])
稚气少女 2024-09-01 19:49:00
>>> l1 = ['a', 'b', 'c', 'd']
>>> l2 = ['c', 'd', 'e']
>>> set(l1) & set(l2)
set(['c', 'd'])
>>> l1 = ['a', 'b', 'c', 'd']
>>> l2 = ['c', 'd', 'e']
>>> set(l1) & set(l2)
set(['c', 'd'])
明月夜 2024-09-01 19:49:00

如果只有唯一元素,则可以使用集合数据类型并使用交集:

s1, s2 = set(l1), set(l2)
num = len(s1.intersection(s2))

If you only have unique elements, you can use the set data type and use intersection:

s1, s2 = set(l1), set(l2)
num = len(s1.intersection(s2))
素罗衫 2024-09-01 19:49:00

使用集合:

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


def list_count_common(list_a, list_b):
    result = len(list(set(list_a) & set(list_b))) ## this is the line that does what you want
    return result

print list_count_common(l1, l2) ## prints 2

Using sets:

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


def list_count_common(list_a, list_b):
    result = len(list(set(list_a) & set(list_b))) ## this is the line that does what you want
    return result

print list_count_common(l1, l2) ## prints 2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文