[英]How do i remove an item from a list and store it into a variable in python
so i want to remove an item from a list and store it into the variable at the same time in python.所以我想从列表中删除一个项目并将它同时存储到 python 中的变量中。 I tried a sample code like this:我尝试了这样的示例代码:
rvals = []
rvals.append("row")
r = rvals.remove("row")
print(r)
but it turns out this doesnt really work and it gives ra NoneType value instead of removing what i wanted and storing it.但事实证明这并没有真正起作用,它给出了 ra NoneType 值,而不是删除我想要的并存储它。 Is there a way to do this?有没有办法做到这一点?
list.remove(x) list.remove(x)
Remove the first item from the list whose value is x.从列表中删除值为 x 的第一项。 It is an error if there is no such item.如果没有这样的项目,这是一个错误。
So, as stated in the docs, you will not get the value returned.因此,如文档中所述,您将不会得到返回的值。
This can help:这可以帮助:
value = "row"
rvals = []
rvals.append(value)
print rvals.pop(rvals.index(value))
Or just use pop() , if you only want to remove and get the last inserted item:或者只是使用pop() ,如果您只想删除并获取最后插入的项目:
value = "row"
rvals = []
rvals.append(value)
print rvals.pop()
Output:输出:
row
Printing a removed element from the list using remove() method generally results in None.使用 remove() 方法打印从列表中删除的元素通常会导致 None。 Hence, a better approach is to, first store the element to be removed and then remove it from the list.因此,更好的方法是首先存储要删除的元素,然后将其从列表中删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.