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

2024-04-27 02:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含列表的列表结果。我只想在结果中添加一个不存在的列表。你知道吗

所以呢

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,那么还有什么选择呢?你知道吗


Tags: 列表inputresultsetappend
3条回答

最简单的解决方案可能是使用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
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)}

您可以使用^{}

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

然后检查:

if ls == no_dupes:
     # Do x

相关问题 更多 >