我有一个列表列表,我想从列表列表中选择重复的元素并打印出来。列表清单如下所示,
a = [[0, 1, 2, 3], [4, 5, 6, 375], [142, 132, 143, 144], [172, 173, 174, 297], [181, 182, 183, 339], [205, 144, 206, 207], [295, 108, 296, 297]]
我尝试使用以下脚本
for i in range(len(a)):
for j in range(1, len(a)):
for m in range(3):
for n in range(3):
if a[i][m] == a[j][n]:
print a[j][n]
但它只是打印
4
5
6
142
132
143
172
173
174
181
182
183
205
144
206
295
108
296
任何人都想尝试并帮助我?
答案 0 :(得分:1)
此代码应该有效:
a = [[0, 1, 2, 3], [4, 5, 6, 375], [142, 132, 143, 144], [172, 173, 174, 297], [181, 182, 183, 339], [205, 144, 206, 207], [295, 108, 296, 297]]
master = [] #this will be a list with every individual element
for array in a: #take every sub-list
for element in array: #do this for every element in the sub-list
if not(element in master): #check that it is not a duplicate
master.append(element) #add the element to your master list
for element in master:
print(element)
答案 1 :(得分:0)
#!/usr/local/bin/python2.7
a = [[0, 1, 2, 3], [4, 5, 6, 375], [142, 132, 143, 144], [172, 173, 174, 297], [181, 182, 183, 339], [205, 144, 206, 207], [295, 108, 296, 297]]
a2 = []
for list1 in a:
a2.extend(list1)
print a2
a2.sort()
for i, n in enumerate(a2):
if i < len(a2)-2 and n == a2[i+1]:
print (n)
我很确定还有其他更有效,更简单的解决方案。等待其他帖子