[英]Python get intersection of elements from list of lists
我有一个list
列表,其中每个list
都是int
列表的string
,如下所示
a = ['[11, -12, -14, 13]',
'[8, 5, -14, 15, 13]',
'[13, 24, -14]']
我需要找到一个常见整数列表(列表的交集),在这种情况下 output 应该是[13, -14]
,因为它们是常见的。
有没有一种简单的方法可以做到这一点,因为各个列表是str
类型,我可以避免第一次迭代到eval
然后找到set
?
map()
ast.literal_eval()
function 覆盖列表b
以安全地将您的字符串列表评估为列表迭代器。map()
set()
构造函数将列表转换为集合。functools.reduce()
和set.intersection()
来找到你的集合的交集。from functools import reduce
from ast import literal_eval
answer = reduce(set.intersection, # 3
map(set, # 2
map(literal_eval, a))) # 1
不是解决它的最漂亮的方法,但它有效。 这将处理 A 中任意数量的列表。
a = ['[11, -12, -14, 13]',
'[8, 5, -14, 15, 13]',
'[13, 24, -14]']
b = []
## this block converts the strings into integers, after this b will be a, but integer lists
for ls in a:
truncated_str = ls.replace("[", "").replace("]", "")
my_list_of_strs = truncated_str.split(",")
my_list_of_ints = []
for num in my_list_of_strs:
my_list_of_ints.append(int(num))
b.append(my_list_of_ints)
## this functions finds commonalites
def in_all_lists(lists, value_to_check):
for my_list in lists:
if value_to_check not in my_list:
return False
return True
common_numbers = []
# checks to see if values are common
for lst in b:
for value in lst:
if value not in common_numbers and in_all_lists(b, value):
common_numbers.append(value)
print(common_numbers) # prints [-14, 13]
通过json
库:
import json
l = [set(json.loads(x)) for x in a]
list(l.pop().intersection(*l))
> [-14, 13]
json.loads()
将列表的字符串表示形式转换为实际列表。 随后,在通过pop()
检索到的该列表的最后一个元素上调用intersection()
,然后通过使用*l
解包将所有集合作为 arguments 传递给intersection()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.