Python:从嵌套列表中删除单个元素 [英] Python: Removing a single element from a nested list

查看:113
本文介绍了Python:从嵌套列表中删除单个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何从嵌套列表中删除某些内容.

I'm having trouble figuring out how to remove something from within a nested list.

例如,我如何从下面的列表中删除x"?

For example, how would I remove 'x' from the below list?

lst = [['x',6,5,4],[4,5,6]]

我尝试了 del lst[0][0],但得到以下结果:

I tried del lst[0][0], but I get the following result:

TypeError: 'str' 对象不支持删除项目.

TypeError: 'str' object doesn't support item deletion.

我也试过 for 循环,但得到同样的错误:

I also tried a for loop, but got the same error:

for char in lst:
    del char[0]

推荐答案

在嵌套列表上使用 pop(i) 函数.例如:

Use the pop(i) function on the nested list. For example:

lst = [['x',6,5,4],[4,5,6]]
lst[0].pop(0)
print lst  #should print [[6, 5, 4], [4, 5, 6]]

完成.

这篇关于Python:从嵌套列表中删除单个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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