简体   繁体   English

Python:从嵌套列表中删除单个元素

[英]Python: Removing a single element from a nested list

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? 例如,如何从下面的列表中删除“x”?

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

I tried del lst[0][0] , but I get the following result: 我尝试了del lst[0][0] ,但是得到了以下结果:

TypeError: 'str' object doesn't support item deletion. TypeError:'str'对象不支持删除项目。

I also tried a for loop, but got the same error: 我也试过一个for循环,但得到了同样的错误:

for char in lst:
    del char[0]

Your code works fine. 你的代码运行正常。 Are you sure lst is defined as [['x',6,5,4],[4,5,6]] ? 你确定lst被定义为[['x',6,5,4],[4,5,6]]吗? Because if it is, del lst[0][0] effectively deletes 'x' . 因为如果是, del lst[0][0]有效地删除'x'

Perhaps you have defined lst as ['x',6,5,4] , in which case, you will indeed get the error you are mentioning. 也许你已经将lst定义为['x',6,5,4] ,在这种情况下,你确实会得到你提到的错误。

Use the pop(i) function on the nested list. 使用嵌套列表上的pop(i)函数。 For example: 例如:

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

Done. 完成。

You can also use "pop". 你也可以使用“pop”。 Eg, 例如,

list = [['x',6,5,4],[4,5,6]]
list[0].pop(0)

will result in 会导致

list = [[6,5,4],[4,5,6]]

See this thread for more: How to remove an element from a list by index in Python? 请参阅此主题以获取更多信息: 如何在Python中通过索引从列表中删除元素?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM