【问题标题】:Unique features between multiple lists多个列表之间的独特功能
【发布时间】:2013-06-06 19:10:51
【问题描述】:

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

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

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

例子:

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

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

有人知道怎么做吗?

【问题讨论】:

  • 很惊讶以前从未有人问过这个问题
  • 这个SO answer 应该可以工作,但由于某种原因,它失败了。

标签: python list set unique


【解决方案1】:

这有帮助吗?我假设一个列表来说明这个例子。但是您可以修改数据结构以满足您的需求

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

编辑(基于一些有用的 cmets):

counts = Counter(chain.from_iterable(list_of_lists))
unique_list = [k for k, c in counts.items() if c == 1]

【讨论】:

  • counts[i]==1 应该是counts[x]==1
  • 另外,不需要map(set, lists_of_lists)chain.from_iterable(list_of_lists) 也一样。
  • 是的,但如果列表中有重复项,它只会消除它们。只是一个小优化。 :)
  • @karthikr 这不是优化
  • +1 但我认为 OP 只希望结果为 [k for k, c in counts.items() if c == 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))

【讨论】:

  • 与我一起工作的另一位研究生使用了此代码,并且效果也很好!感谢您的建议
  • 你能帮忙回答一个相关的SO question吗?
【解决方案3】:

在推导中使用集合差分

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

【讨论】:

    【解决方案4】:

    好的,我是 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)
    

    【讨论】:

      猜你喜欢
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      相关资源
      最近更新 更多