[英]Removing element in a list
list = [0, 1, 2, 8, 2, 9, 2]
Is there a way to remove the element 2
, exactly one time?有没有办法一次删除元素2
?
So you will get:所以你会得到:
list = [0, 1, 2, 8, 9, 2]
I tried to work with index()
but I didn't found it.我尝试使用index()
但我没有找到它。
It can be a RANDOM 2
.它可以是 RANDOM 2
。
So I can't use remove()
or pop()
because it will not remove the number 2
on a random position.所以我不能使用remove()
或pop()
因为它不会删除随机位置上的数字2
。
This works这有效
list.remove(2)
L.remove(value) -- remove first occurrence of value. L.remove(value) -- 删除第一次出现的值。
Raises ValueError if the value is not present.如果值不存在,则引发 ValueError。
Use del
or pop
使用del
或pop
For example,例如,
del list[2]
or或者
list.pop(2)
The difference between del and pop is that del 和 pop 的区别在于
del
is overloaded. del
过载。
for example, del a[1:3] means deletion of elements 1 and 3例如 del a[1:3] 表示删除元素 1 和 3
To randomly remove occurrence of 2
随机删除出现的2
Notes:笔记:
2
ie [i for i, j in enumerate(lst) if j == 2]
我们创建一个数字2
的索引列表,即[i for i, j in enumerate(lst) if j == 2]
Code:代码:
import random
lst = [0, 1, 2, 8, 2, 9, 2]
lst.pop(random.choice([i for i, j in enumerate(lst) if j == 2]))
print lst
output:输出:
[0, 1, 8, 2, 9, 2]
Note that you're shadowing the built-in list
.请注意,您正在隐藏内置list
。 Apart from that index
works just fine:除了该index
工作正常:
>>> li = [0, 1, 2, 8, 2, 9, 2]
>>> li.pop(li.index(2))
2
>>> li
[0, 1, 8, 2, 9, 2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.