
[英]I need to remove the elements of the list which are greater than 1 in python
[英](Python) I need to remove the duplicate elements in a list (use remove funct; avoid typecasting). Trying to determine why my solution is incorrect
规范:我想使用 remove 函数(在列表中)并且我更愿意避免类型转换。
l = [2, 3, 3, 4, 6, 4, 6, 5]
q=len(l)
for i in range (0, q):
for g in range (i+1, q):
if l[g]==l[i]:
q-=1 #decremented q to account for reduction in list size.
l.remove(l[g])
print(l)
错误: if l[g]==l[i]:
IndexError:列表索引超出范围
我知道以前用户也问过类似的问题。 由于其中不存在上述限制,我想请您将此视为一个单独的问题。 谢谢!
>>> l = [2, 3, 3, 4, 6, 4, 6, 5]
>>> s = set(l)
>>> t = sorted(s)
>>> print(t)
[2, 3, 4, 5, 6]
使用set
是过滤收藏的一种简单而直接的方法。 如果您不需要特定顺序的列表,您可以只使用该列表中的集合。 sorted
函数返回一个列表(使用默认排序)。
既然你提到你不想要类型转换,所以我的解决方案是使用while loop
l = [2, 3, 3, 4, 6, 4, 6, 5]
q=len(l)
i = 0
while i<len(l):
g = i+1
while (g < q):
if l[g]==l[i]:
q-=1 #decremented q to account for reduction in list size.
l.remove(l[g])
g += 1
i += 1
print(l)
现在,让我解释一下您的代码中的问题。 当您使用 range 函数时,它会在循环的第一次运行时保存起始值和结束值,因此即使您之后在循环中更改了限制,它仍然不会更改范围循环,因此最终您会得到index out of bounds
错误。
希望这对你有帮助:)
您的解决方案不起作用,因为 range() 存储 q 的值,并且稍后会忽略 q 值的变化。 例如:
>>> m = 10
>>> for i in range(m):
... m=0
... print(i)
...
0
1
2
3
4
5
6
7
8
9
即使我改变了 m,range() 仍然会在循环中运行 10 次。 因此,当您更改列表的大小时,即使您更改 q,您仍然会尝试到达不再存在的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.