首页 > 解决方案 > for循环(python)中的for循环不起作用

问题描述

该程序应该从列表中删除重复元素,但它似乎不起作用,

 import random
 def func():
    a=random.sample(range(10),7)
    b=random.sample(range(10),6)
    list=a+b
    print(list)
    print(len(list))
    for x in list:
        for y in list:
            if x==y and list.index(x)!=list.index(y):
                list.remove(y)
print(func())

输出

[2, 6, 4, 7, 0, 9, 3, 8, 3, 5, 7, 0, 1]
13
None

标签: pythonpython-3.xlistnested-loops

解决方案


我会把它作为答案。但请注意,您可能应该澄清您的标题。

首先,如果您的主要目标是删除重复项,那么您最好的选择是将您的list设置为 a,set因为set内部不允许重复。

a=random.sample(range(10),7)
b=random.sample(range(10),6)
my_list=a+b
print(set(list))

另请注意,您可以使用它来获得更好的输出:

a=random.sample(range(10),7)
b=random.sample(range(10),6)
my_list=a+b
print (','.join(str(v) for v in set(my_list)))

推荐阅读