如何从列表中删除一个“列”?
给定:
L = [
["a","b","C","d"],
[ 1, 2, 3, 4 ],
["w","x","y","z"]
]
我想删除“列” 2,得到:
L = [
["a","b","d"],
[ 1, 2, 4 ],
["w","x","z"]
]
有没有类似的切片或删除方法可以实现这个功能?例如:
del L[:][2]
你可以循环。
for x in L:
del x[2]
如果你在处理大量数据,你可以使用支持复杂切片的库。不过,一个简单的列表嵌套并不能进行切片。
只需遍历该列表并删除您想要删除的索引。
例如:
for sublist in list:
del sublist[index]
>>> 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个位置上的每个元素。
您已经获得了被移除的元素列表和不包含这些元素的主列表。
稍微扭曲的版本:
index = 2 # Delete column 2
[(x[0:index] + x[index+1:]) for x in L]
[(x[0], x[1], x[3]) for x 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']]
L = [['a', 'b', 'C', 'd'], [1, 2, 3, 4], ['w', 'x', 'y', 'z']]
_ = [i.remove(i[2]) for i in L]
remove
将返回[2,1,3]
而不是[1,2,3]
。 - DSMfilter_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
是要删除元素的索引。
new_L = [list(row) for row in L]
... 这只是一种方法,它将创建每行的浅层副本,因此当您修改new_L
时,原始的L
不会被修改。 - Dietrich Epp