[英]I want to write a function that takes an integr and returns a list of all of its multiplicators
[英]I want to write a function that takes a list and returns it with all duplicates removed, without creating another list or string
我已经尝试过了,它给出了应该给出的输出[[1,3,2]),但是问题是它不断输出输出无限次而没有停顿,是否有任何解决方案都没有改变代码的思想。
a= [1,2,2,2,1,3,2]
def rem_dup(L):
while len(L):
for i in L:
y= L.count(i)
if y>1:
L.remove(i)
print L
rem_dup(a)
除非此功能的重点是锻炼python技能,否则听起来好像您需要set
。 集就像一个列表,但不允许重复值。 如果您希望最终的数据结构成为列表,则可以执行以下操作:
final_list = list(set(original_list))
安全地执行此操作的一种方法是反向遍历列表,并仅从背面删除:
>>> for i in range(len(a) - 1, -1, -1):
... if a.count(a[i]) > 1:
... del a[i]
...
>>> a
[1, 2, 3]
但这将是多项式时间,因为a.count
是线性的, del a[i]
也是如此。
while len(L)
将永远是只要真正为L
曾在它的东西开始
在for
循环中使用L时修改L会导致项目被跳过,因此某些输入存在错误。
如果解决了该问题,则不需要while循环。
只要中的项目a
可哈希的,而且您不介意开始时其余项目的顺序不同,则可以创建中间set
并就地替换原始内容。
a[:] = set(a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.