从Python的嵌套列表中删除列 [英] Remove a column from a nested list in Python

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

问题描述

我需要帮助弄清楚如何从嵌套列表中删除列"以对其进行修改.

I need help figuring how to work around removing a 'column' from a nested list to modify it.

说我有

L = [[1,2,3,4],
     [5,6,7,8],
     [9,1,2,3]]

我想删除第二列(因此值为2、6、1)以获取:

and I want to remove the second column (so values 2,6,1) to get:

L = [[1,3,4],
     [5,7,8],
     [9,2,3]]

我一直坚持只删除一列就如何修改列表.我以前做过类似的事情吗?除非我们打印它,否则在这种情况下它当然不起作用,因为我相信中断与列表中我想要的其他值冲突.

I'm stuck with how to modify the list with just taking out a column. I've done something sort of like this before? Except we were printing it instead, and of course it wouldn't work in this case because I believe the break conflicts with the rest of the values I want in the list.

def L_break(L):

i = 0
while i < len(L):
    k = 0
    while k < len(L[i]):
        print( L[i][k] , end = " ")
        if k == 1:
            break
        k = k + 1
    print()
    i = i + 1

那么,您将如何修改此嵌套列表? 将其与我发布的代码进行比较,我的想法是否在正确的地方?或者这需要有所不同吗?

So, how would you go about modifying this nested list? Is my mind in the right place comparing it to the code I have posted or does this require something different?

推荐答案

您可以使用

You can simply delete the appropriate element from each row using del:

L = [[1,2,3,4],
     [5,6,7,8],
     [9,1,2,3]]

for row in L:
    del row[1]  # 0 for column 1, 1 for column 2, etc.

print L
# outputs [[1, 3, 4], [5, 7, 8], [9, 2, 3]]

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

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