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

发布于 2024-10-21 14:31:09 字数 308 浏览 2 评论 0原文

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

例如,如何从下面的列表中删除“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

幼儿园老大 2024-10-28 14:31:09

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

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

完成。

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]]

Done.

橪书 2024-10-28 14:31:09

你的代码工作正常。您确定 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.

缘字诀 2024-10-28 14:31:09

您也可以使用“流行”。例如,

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

将导致

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

查看此线程以了解更多信息: 如何在Python中通过索引从列表中删除元素?

You can also use "pop". E.g.,

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文