python - 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
解决方案
我会把它作为答案。但请注意,您可能应该澄清您的标题。
首先,如果您的主要目标是删除重复项,那么您最好的选择是将您的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)))
推荐阅读
- java - intellij 想法,maven spring-boot:run 不会:'t stop
- xamarin - 所有设备的相同视图大小
- javascript - 在 React 中触发时移动对象(不同宽度的轮播)
- jenkins - jenkins 上的登录类型选择有什么区别?
- java - 如何使用 Java Spring 从 XML 制作对象列表?
- c++ - 为什么我会得到错误的“i”整数值?
- reactjs - 使用 React 创建多页面组件
- reactjs - 在 React Native 上进行用户身份验证的最佳方法?
- python - 内部类的调用函数
- tensorflow - ConvLSTM2d 在 colab GPU 上的运行速度比 CPU 慢