19

如何从列表列表中删除“列”?
鉴于:

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

我想删除“列”2以获得:

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

是否有slicedel方法可以做到这一点?就像是:

del L[:][2]
4

9 回答 9

13

你可以循环。

for x in L:
    del x[2]

如果您要处理大量数据,则可以使用支持复杂切片的库。但是,简单的列表列表不会切片。

于 2012-11-06T04:38:37.767 回答
7

只需遍历该列表并删除要删除的索引。

例如

for sublist in list:
    del sublist[index]
于 2012-11-06T04:40:25.647 回答
4

稍微扭曲的版本:

index = 2  # Delete column 2 
[(x[0:index] + x[index+1:]) for x in L]
于 2012-11-06T04:53:12.777 回答
4

您可以通过列表理解来做到这一点:

>>> removed = [ l.pop(2) for l in L ]
>>> print L
[['a', 'b', 'd'], [1, 2, 4], ['w', 'x', 'z']]
>>> print removed
['d', 4, 'z']

它循环列表并弹出位置 2 中的每个元素。

您已经删除了元素列表和没有这些元素的主列表。

于 2016-02-10T11:25:40.383 回答
2
[(x[0], x[1], x[3]) for x in L]

It works fine.

于 2012-11-06T09:34:11.893 回答
1
L = [['a', 'b', 'C', 'd'], [1, 2, 3, 4], ['w', 'x', 'y', 'z']]
_ = [i.remove(i[2]) for i in L]
于 2012-11-06T16:29:55.803 回答
1

这是删除您想要的任何列的一种非常简单的方法。

L = [
["a","b","C","d"],
[ 1,  2,  3,  4 ],
["w","x","y","z"]
]
temp = [[x[0],x[1],x[3]] for x in L] #x[column that you do not want to remove]
print temp
O/P->[['a', 'b', 'd'], [1, 2, 4], ['w', 'x', 'z']]
于 2012-11-06T04:47:25.557 回答
0

如果您不介意创建新列表,则可以尝试以下操作:

filter_col = lambda lVals, iCol: [[x for i,x in enumerate(row) if i!=iCol] for row in lVals]

filter_out(L, 2)
于 2012-11-06T04:46:18.943 回答
0

替代方案pop()

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

n是要删除的元素的索引。

于 2019-06-16T03:10:01.803 回答