Python 如何检查列表列表中是否存在重复列表?
我有一个包含列表的列表结果。我只想在结果中添加一个不存在的列表 所以 现在,Python 如何检查列表列表中是否存在重复列表?,python,list,set,mutable,Python,List,Set,Mutable,我有一个包含列表的列表结果。我只想在结果中添加一个不存在的列表 所以 现在,RESULT.append(input)给出 RESULT = [[5,6], [4,5,8], [1,2,3]] 现在,如果我尝试附加[5,6]它不应该被添加,因为它已经存在了 我不能在这里使用集合,那么还有什么选择呢?您可以使用: def add(data_, value): if value not in data_: data_.append(value) data = [[5, 6]
RESULT.append(input)
给出
RESULT = [[5,6], [4,5,8], [1,2,3]]
现在,如果我尝试附加[5,6]
它不应该被添加,因为它已经存在了
我不能在这里使用集合
,那么还有什么选择呢?您可以使用:
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)}
然后检查它:
if ls == no_dupes:
# Do x
假设在追加结果之后。追加(输入)
此特定代码的基本思想:
检查:
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)
i=0
计数=0
而我最简单的解决方案可能是使用if
语句首先检查[5,6]
是否已经在结果中,如果没有,则添加它,否则继续,可能会向用户报告它是重复的且没有添加:
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
结果:[[5,6],[4,5,8],[1,2,3]]
回溯(最近一次呼叫最后一次):
文件“main.py”,第15行,在
raise(异常(f'{l}是重复的,因此未追加'))
异常:[5,6]是重复的,因此未追加
到目前为止你都试了些什么?为什么不能用一套呢?@alec_a是的,我理解,但无法确定哪一套解决了问题。有点像是用另一种方式解决了这个问题,但会对答案进行另一种解读,并标记:-)@Atihska谢谢!顺便说一句,如果你找到了一个不同的方法来解决它,你可能想发布一个你自己问题的答案。它可以帮助未来的读者(如果他们倾向于提高投票率,还可以为你赢得一些代表)
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)
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