瑞子 发表于 2021-5-21 04:33:02

如何在2个不同的列表中找到常见元素?

我有这个列表:A[(7.5,),(17.5,),(22.5,),(25.0,),(27.5,),(30.0),(37.5,),(40.0,)]B[(17.5 ),(22.5,),(25.0),(27.5),(30.0),(37.5,),(40.0),)]

我想在列表
中找到相同的元素的数量 我尝试了这些方法,但结果始终为零:
list1_as_set = set(A)
intersection = list1_as_set.intersection(B)
intersection_as_list = list(intersection)我也试过了:commonalities = set(A) - (set(A) - set(B))但结果是空的...
如何在2个不同的列表中找到常见元素?

猪宝宝婷婷 发表于 2021-5-23 22:31:53

A = [(7.5,), (17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,)]
B = [(17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,), (42.5,)]

list(set(A).intersection(B))

沸云 发表于 2021-5-30 06:36:08

>>> A = [(7.5,), (17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,)]
>>> B = [(17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,), (42.5,)]
>>> set(A).union(set(B))
{(37.5,), (40.0,), (30.0,), (27.5,), (17.5,), (7.5,), (42.5,), (25.0,), (22.5,)}
>>>
>>>
>>> # With lists better formatted:
>>> A =
>>> B =
>>> set(A).union(set(B))
{37.5, 7.5, 40.0, 42.5, 17.5, 22.5, 25.0, 27.5, 30.0}
>>>
页: [1]
查看完整版本: 如何在2个不同的列表中找到常见元素?