如何从列表列表中删除“列”?
鉴于:
L = [
["a","b","C","d"],
[ 1, 2, 3, 4 ],
["w","x","y","z"]
]
我想删除“列”2以获得:
L = [
["a","b","d"],
[ 1, 2, 4 ],
["w","x","z"]
]
是否有slice或del方法可以做到这一点?就像是:
del L[:][2]
你可以循环。
for x in L:
del x[2]
如果您要处理大量数据,则可以使用支持复杂切片的库。但是,简单的列表列表不会切片。
只需遍历该列表并删除要删除的索引。
例如
for sublist in list:
del sublist[index]
稍微扭曲的版本:
index = 2 # Delete column 2
[(x[0:index] + x[index+1:]) for x in L]
您可以通过列表理解来做到这一点:
>>> 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 中的每个元素。
您已经删除了元素列表和没有这些元素的主列表。
[(x[0], x[1], x[3]) for x in L]
It works fine.
L = [['a', 'b', 'C', 'd'], [1, 2, 3, 4], ['w', 'x', 'y', 'z']]
_ = [i.remove(i[2]) for i in L]
这是删除您想要的任何列的一种非常简单的方法。
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']]
如果您不介意创建新列表,则可以尝试以下操作:
filter_col = lambda lVals, iCol: [[x for i,x in enumerate(row) if i!=iCol] for row in lVals]
filter_out(L, 2)
替代方案pop()
:
[x.__delitem__(n) for x in L]
这n
是要删除的元素的索引。