Python:从嵌套列表中删除单个元素
我无法弄清楚如何从嵌套列表中删除某些内容。
例如,如何从下面的列表中删除“x”?
lst = [['x',6,5,4],[4,5,6]]
我尝试了 del lst[0][0]
,但得到以下结果:
类型错误:“str”对象不支持项目删除。
我也尝试了 for 循环,但得到了同样的错误:
for char in lst:
del char[0]
I'm having trouble figuring out how to remove something from within a nested list.
For example, how would I remove 'x' from the below list?
lst = [['x',6,5,4],[4,5,6]]
I tried del lst[0][0]
, but I get the following result:
TypeError: 'str' object doesn't support item deletion.
I also tried a for loop, but got the same error:
for char in lst:
del char[0]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在嵌套列表上使用
pop(i)
函数。例如:完成。
Use the
pop(i)
function on the nested list. For example:Done.
你的代码工作正常。您确定
lst
定义为[['x',6,5,4],[4,5,6]]
吗?因为如果是,del lst[0][0]
会有效删除'x'
。也许您已将
lst
定义为['x',6,5,4]
,在这种情况下,您确实会收到您提到的错误。Your code works fine. Are you sure
lst
is defined as[['x',6,5,4],[4,5,6]]
? Because if it is,del lst[0][0]
effectively deletes'x'
.Perhaps you have defined
lst
as['x',6,5,4]
, in which case, you will indeed get the error you are mentioning.您也可以使用“流行”。例如,
将导致
查看此线程以了解更多信息: 如何在Python中通过索引从列表中删除元素?
You can also use "pop". E.g.,
will result in
See this thread for more: How to remove an element from a list by index in Python?