如何在列表列表中查找重复项?

qgelzfjb  于 2022-10-22  发布在  Python
关注(0)|答案(3)|浏览(152)

我有一个类中的键绑定列表,如下所示:

self.key_bind_list = [["A", "B"], ["C"], ["SHIFT", "NUM6", "NUM7"], ["A", "B"], ["A", "B", "C"]]
  • 在这种情况下,子列表["A", "B"]应该检测到重复,而不是["A", "B"]["A", "B", "C"]

我想检查主列表中是否有重复项(假设每个子列表中的键都是唯一的,顺序并不重要,我不需要知道哪些键不是唯一的)
我已尝试在以下内容中使用set方法:

if(len(self.key_bind_list) != len(set(self.key_bind_list))):

这给了我一个unhashable type: 'list'错误。

5lwkijsr

5lwkijsr1#

假设您只想检查是否存在重复项,并打印出哪些子列表包含重复项,那么可以使用一种方法来处理包含set元素的列表,例如:

key_bind_list = [["A", "B"], ["C"], ["SHIFT", "NUM6", "NUM7"], ["B", "A"], ["A", "B", "C"]]

seen = []

for i, sublist in enumerate(key_bind_list):
    s = set(sublist)
    if s in seen:
        print(f'index {i}: there are duplicates in {sublist}')
    seen.append(s)

输出:

index 3: there are duplicates in ['B', 'A']

如果列表中的any子列表与另一个子列表重复(无论顺序如何),只需返回bool值,您可以这样做:

def has_duplicates(L: list[list]) -> bool:
    seen = []

    for sublist in L:
        s = set(sublist)
        if s in seen:
            return True
        seen.append(s)

    return False

print(has_duplicates(key_bind_list))
k2fxgqgv

k2fxgqgv2#

使用collections.Counter。它很适合建模多集。要绕过unhashable type错误,需要对tuple进行强制转换,但这会使匹配对子列表的排序有意义

from collections import Counter

lst = [["A", "B"], ["C"], ["SHIFT", "NUM6", "NUM7"], ["A", "B"]]

c = Counter(map(tuple, lst))

for k, v in c.items():
    if v > 1:
        print(k, v)

通过使用一组相等标准检查所有对,即所有项都等于某个顺序:

from itertools import combinations

lst = [["A", "B"], ["C"], ["SHIFT", "NUM6", "NUM7"], ["A", "B"], ["A", "B", "C"]]

for s1, s2 in combinations(map(set, lst), 2):
   if s1 == s2:
      print(s1)

# {'A', 'B'}
lzfw57am

lzfw57am3#

len(set([tuple(sorted(x)) for x in L])) != len(L)

返回True表示列表列表中存在重复项。

  • 输出:
>>> L = [["A", "B"], ["C"], ["SHIFT", "NUM6", "NUM7"], ["A", "B"], ["A", "B", "C"]]
>>> print(len(set([tuple(sorted(x)) for x in L])) != len(L))
True

>>> L = [['A', 'B'], ['C'], ['SHIFT', 'NUM6', 'NUM7'], ['A', 'B', 'C']]
>>> print(len(set([tuple(sorted(x)) for x in L])) != len(L))
False

>>> L = [["A", "B"], ["C"], ["SHIFT", "NUM6", "NUM7"], ["B", "A"], ["A", "B", "C"]]
>>> print(len(set([tuple(sorted(x)) for x in L])) != len(L))
True

相关问题