How do I delete the Nth list item from a list of l

2020-02-10 14:00发布

How do I delete a "column" from a list of lists?
Given:

L = [
     ["a","b","C","d"],
     [ 1,  2,  3,  4 ],
     ["w","x","y","z"]
    ]

I would like to delete "column" 2 to get:

L = [
     ["a","b","d"],
     [ 1,  2,  4 ],
     ["w","x","z"]
    ]

Is there a slice or del method that will do that? Something like:

del L[:][2]

9条回答
放荡不羁爱自由
2楼-- · 2020-02-10 14:55
L = [['a', 'b', 'C', 'd'], [1, 2, 3, 4], ['w', 'x', 'y', 'z']]
_ = [i.remove(i[2]) for i in L]
查看更多
一纸荒年 Trace。
3楼-- · 2020-02-10 14:59

An alternative to pop():

[x.__delitem__(n) for x in L]

Here n is the index of the elements to be deleted.

查看更多
成全新的幸福
4楼-- · 2020-02-10 15:00

A slightly twisted version:

index = 2  # Delete column 2 
[(x[0:index] + x[index+1:]) for x in L]
查看更多
登录 后发表回答