我有2个昏暗的列表,其中某些列表中包含重复的元素,如下所示
myData=[['a',1,10],['b',2,20],['a',3,30],['a',4,40]]
我想做:
我写了下面的代码:
duplicatedLists=[]
uniqueLists=[]
myData=[['a',1,10],['b',2,20],['a',3,30],['a',4,40]]
for row in myData:
print(row[0])
if(row[0] not in uniqueLists):
uniqueLists.append(row)
else:
duplicatedLists.append(row)
print(uniqueLists)
print(duplicatedLists)
so my result should be:
uniqueLists=[['a',1,10],['b',2,20]]
duplicatedLists=[[['a',3,30],['a',4,40]].
但是我得到这个结果:
[['a', 1, 10], ['b', 2, 20], ['a', 3, 30], ['a', 4, 40]]
[]
答案 0 :(得分:0)
此行if(row[0] not in uniqueLists):
中有问题,您正在检查第一个元素,但要将整个子列表附加到uniqueLists
列表中
代替尝试:
myData=[['a',1,10],['b',2,20],['a',3,30],['a',4,40]]
duplicatedLists=[]
uniqueLists=[]
check_val = set()
for i in myData:
if i[0] not in check_val: #Check if value in set.
uniqueLists.append(i)
check_val.add(i[0]) #! Add only first element to perform check.
else:
duplicatedLists.append(i)
print(uniqueLists) #[['a', 1, 10], ['b', 2, 20]]
print(duplicatedLists) #[['a', 3, 30], ['a', 4, 40]]