我目前的输出[1,2,3,4,5,6] [2,1,3,4,5,6] [3,2,1,4,5,6] ...... [6,5,4,3,2,1] 所有数字都相同,但我只想要这个输出 一个[1,2,3,4,5,6]我该怎么做
import os
import sys
numbers=[1,2,3,4,5,6]
x=[]
for i1 in numbers:
for i2 in numbers:
for i3 in numbers:
for i4 in numbers:
for i5 in numbers:
for i6 in numbers:
if i1 not in (i2,i3,i4,i5,i6) and i2 not in (i1,i3,i4,i5,i6) and i3 not in (i1,i2,i4,i5,i6) and i4 not in (i1,i2,i3,i5,i6) and i5 not in (i1,i2,i3,i4,i6) and i6 not in (i1,i2,i3,i4,i5):
x.append([i1,i2,i3,i4,i5,i6])
i=0
while i < len(x):
print x[i]
i=i+1
答案 0 :(得分:0)
这是一个相当不明确的问题,但要删除列表中的重复项:
nums = [1,2,3,3,4,5,6]
x = []
for i in nums:
if i not in x:
x.append(i)
[print(i) for i in x] # output -> 1 2 3 4 5 6
只能从几个列表中获取独特内容:
nums = [1,2,3,3,4,5,6]
nums2 = [2,1,3,4,4,5,7,8]
lists = nums + nums2
x = []
for i in lists:
if i not in x:
x.append(i)
[print(i) for i in x] # output -> 1 2 3 4 5 6 7 8
只获取一组唯一的数字:
nums1 = [1,2,3,4,5,6]
nums2 = [3,2,1,6,5,4]
nums3 = [4,3,2,5,1,6]
nums4 = [2,3,4,5,6,7]
s1 = set(nums1)
s2 = set(nums2)
s3 = set(nums3)
s4 = set(nums4)
sets = [s1, s2, s3, s4]
uniq = []
for s in sets:
if s not in uniq:
uniq.append(s)
for u in uniq:
[print(i, end=' ') for i in u]
print() # output -> {1,2,3,4,5,6} and {2,3,4,5,6,7}
不需要使用集合,但会确保原始列表中没有重复项,并且在其他方面也会更容易。
答案 1 :(得分:0)
set()
它!
只需在要删除重复项的列表中使用set()
即可。然后list()
将它投射到列表中。
答案 2 :(得分:0)
您可以在python中使用list comprehensions来实现此目的。
假设您有多个列表,并希望将这些列表中的所有唯一元素放入一个数组中,您可以这样编码。
number_list_1 = [1,2,3,4,5]
number_list_2 = [4,3,2,1,6]
number_list_3 = [2,4,1,3,7]
no_dupes = []
[no_dupes.append(item) for item in number_list_1 if item not in no_dupes]
[no_dupes.append(item) for item in number_list_2 if item not in no_dupes]
[no_dupes.append(item) for item in number_list_3 if item not in no_dupes]
print str(no_dupes)
这将返回:[1, 2, 3, 4, 5, 6, 7]