7

我试图找出 5 个不同列表之间的独特差异。

我已经看到了多个如何查找两个列表之间差异的示例,但无法将其应用于多个列表。

很容易找到 5 个列表之间的相似之处。

例子:

list(set(hr1) & set(hr2) & set(hr4) & set(hr8) & set(hr24))

但是,我想弄清楚如何确定每组的独特功能。

有谁知道如何做到这一点?

4

4 回答 4

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]
于 2013-06-11T02:25:49.913 回答
4

这个怎么样?假设我们有输入列表[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))
于 2013-06-11T02:41:51.993 回答
1

在理解中使用集合差分

def f(lol):
  return [[*set(lol[i]).difference(*lol[:i], *lol[i+1:])] for i in range(len(lol))]

示例 #1

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]]

示例 #2

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]]
于 2018-11-01T16:31:55.830 回答
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)
于 2013-06-11T22:55:31.580 回答