如何从列表中删除项目并将其存储到python中的变量中 [英] How do i remove an item from a list and store it into a variable in python

查看:67
本文介绍了如何从列表中删除项目并将其存储到python中的变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想从列表中删除一个项目,并将其同时存储在python中的变量中.我尝试了这样的示例代码:

so i want to remove an item from a list and store it into the variable at the same time in python. I tried a sample code like this:

rvals = []
rvals.append("row")
r = rvals.remove("row")
print(r)

,但事实证明这确实不起作用,它为r提供了NoneType值,而不是删除我想要的并存储它.有办法吗?

but it turns out this doesnt really work and it gives r a NoneType value instead of removing what i wanted and storing it. Is there a way to do this?

推荐答案

list.remove(x)

从列表中删除值为x的第一项.这是一个错误如果没有这样的项目.

Remove the first item from the list whose value is x. It is an error if there is no such item.

因此,如文档中所述,您将不会获得返回的值.

So, as stated in the docs, you will not get the value returned.

这可以帮助您

value = "row"

rvals = []
rvals.append(value)
print rvals.pop(rvals.index(value))

或者,如果您只想删除并获取最后插入的项目,则只需使用 pop():

Or just use pop(), if you only want to remove and get the last inserted item:

value = "row"

rvals = []
rvals.append(value)
print rvals.pop()

输出:

row

这篇关于如何从列表中删除项目并将其存储到python中的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆