gpt4 book ai didi

python - 在python中查找两个字符串列表的交集

转载 作者:太空狗 更新时间:2023-10-30 02:10:38 24 4
gpt4 key购买 nike

我已经经历了Find intersection of two lists? , Intersection of Two Lists Of Strings , Getting intersection of two lists in python .但是,我无法解决使用 Python 查找两个字符串列表之间的交集的问题。

我有两个变量。

A = [['11@N3'], ['23@N0'], ['62@N0'], ['99@N0'], ['47@N7']]

B = [['23@N0'], ['12@N1']]

如何找到'23@N0'同时属于A和B的一部分?

我尝试使用 http://www.saltycrane.com/blog/2008/01/how-to-find-intersection-and-union-of/ 中提到的 intersect(a,b)但是,当我尝试将 A 转换为集合时,它会抛出一个错误:

File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'

为了将其转换为集合,我使用了 TypeError: unhashable type: 'list' when using built-in set function 中的方法可以使用

转换列表的位置
result = sorted(set(map(tuple, A)), reverse=True)

成一个元组,然后元组可以转换成一个集合。但是,这会返回一个空集作为交集。

你能帮我找到路口吗?

最佳答案

您可以使用 compiler.ast 模块的 flatten 函数来展平您的子列表,然后像这样应用集合交集

from compiler.ast import flatten

A=[['11@N3'], ['23@N0'], ['62@N0'], ['99@N0'], ['47@N7']]
B=[['23@N0'], ['12@N1']]

a = flatten(A)
b = flatten(B)
common_elements = list(set(a).intersection(set(b)))
common_elements
['23@N0']

关于python - 在python中查找两个字符串列表的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28691406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com