如何检查列表列表中是否存在重复列表?

How can I check if there is a duplicate list in a list of lists?

我有一个包含列表的列表结果。我只想在 RESULT 不存在的情况下将其添加到 RESULT。

所以

input = [1,2,3]
RESULT = [[5,6], [4,5,8]]

现在,RESULT.append(input) 给出

RESULT = [[5,6], [4,5,8], [1,2,3]]

现在,如果我尝试 append [5,6] 它不应该被添加,因为它已经存在。

我不能在这里使用 set 那么有什么选择呢?

def add(data_, value):
    if value not in data_:
        data_.append(value)

data = [[5, 6], [4, 5, 8]]
print(data)  # [[5, 6], [4, 5, 8]]
add(data, [1, 2, 3])
print(data)  # {(5, 6), (4, 5, 8), (1, 2, 3)}
add(data, [5, 6])
print(data)  # {(5, 6), (4, 5, 8), (1, 2, 3)}

您可以使用 itertools.groupby():

no_dupes = list(ls for ls, _ in itertools.groupby(ls))

然后对照一下:

if ls == no_dupes:
     # Do x
input = [1,2,3]
RESULT = [[5,6], [4,5,8]]

假设在附加RESULT.append(input)

之后
RESULT=[[5,6], [4,5,8], [1,2,3]]

此特定代码的基本思想:

用于检查:

i=0    
count=0
while i<3:
  if input == RESULT[i]:
     count=count+1
  i = i + 1
if count==0:
    RESULT.append(input)
print(RESULT)

最简单的解决方案可能是使用 if 语句首先检查 [5,6] 是否已经在 RESULT 中,如果没有,则 append ,否则继续上,可能会向用户报告它是重复的而不是附加的:

myinput = [1,2,3]
RESULT = [[5,6], [4,5,8]]

RESULT.append(myinput)

l = [5,6]

if l not in RESULT:
    RESULT.append(l)
else:
    # Do something with RESULT 
    pass # or
    # print('Duplicate not appended')
    print(f'RESULT: {RESULT}')
    raise(Exception(f'{l} is a duplicate and thus was not appended'))

输出:

RESULT: [[5, 6], [4, 5, 8], [1, 2, 3]]
Traceback (most recent call last):
  File "main.py", line 15, in <module>
    raise(Exception(f'{l} is a duplicate and thus was not appended'))
Exception: [5, 6] is a duplicate and thus was not appended