我有一个列表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
最简单的解决方案可能是使用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
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)