我试图找到5个不同列表之间的独特差异。
我已经看到了多个如何找到两个列表之间的差异但未能将其应用于多个列表的示例。
很容易找到5个列表之间的相似之处。
示例:
list(set(hr1) & set(hr2) & set(hr4) & set(hr8) & set(hr24))
但是,我想弄清楚如何确定每组的独特功能。
有谁知道怎么做?
答案 0 :(得分:4)
这有用吗?我假设一个列表列表来说明这个例子。但您可以修改数据结构以满足您的需求
from collections import Counter
from itertools import chain
list_of_lists = [
[0,1,2,3,4,5],
[4,5,6,7,8,8],
[8,9,2,1,3]
]
counts = Counter(chain.from_iterable(map(set, list_of_lists)))
uniques_list = [[x for x in lst if counts[x]==1] for lst in list_of_lists]
#uniques_list = [[0], [6, 7], [9]]
编辑(基于一些有用的评论):
counts = Counter(chain.from_iterable(list_of_lists))
unique_list = [k for k, c in counts.items() if c == 1]
答案 1 :(得分:2)
这是怎么回事?假设我们有输入列表[1, 2, 3, 4]
,[3, 4, 5, 6]
和[3, 4, 7, 8]
。我们希望从第一个列表中提取[1, 2]
,从第二个列表中提取[5, 6]
,从第三个列表提取[7, 8]
。
from itertools import chain
A_1 = [1, 2, 3, 4]
A_2 = [3, 4, 5, 6]
A_3 = [3, 4, 7, 8]
# Collect the input lists for use with chain below
all_lists = [A_1, A_2, A_3]
for A in (A_1, A_2, A_3):
# Combine all the lists into one
super_list = list(chain(*all_lists))
# Remove the items from the list under consideration
for x in A:
super_list.remove(x)
# Get the unique items remaining in the combined list
super_set = set(super_list)
# Compute the unique items in this list and print them
uniques = set(A) - super_set
print(sorted(uniques))
答案 2 :(得分:0)
好的,我是python的初学者,并且无法很好地遵循上面的建议,但能够使用以下代码找出我的问题,基本上只是一堆成对的比较。
x1 = [x for x in hr1 if x not in hr2]
x2 = [x for x in x1 if x not in hr4]
x3 = [x for x in x2 if x not in hr8]
x4 = [x for x in x3 if x not in hr24]
len(x4)
答案 3 :(得分:0)
def f(lol):
return [[*set(lol[i]).difference(*lol[:i], *lol[i+1:])] for i in range(len(lol))]
list_of_lists = [
[0,1,2,3,4,5],
[4,5,6,7,8,8],
[8,9,2,1,3]
]
f(list_of_lists)
[[0], [6, 7], [9]]
A_1 = [1, 2, 3, 4]
A_2 = [3, 4, 5, 6]
A_3 = [3, 4, 7, 8]
all_lists = [A_1, A_2, A_3]
f(all_lists)
[[1, 2], [5, 6], [7, 8]]