问题
In Python, 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]
回答1:
You could loop.
for x in L:
del x[2]
If you're dealing with a lot of data, you can use a library that support sophisticated slicing like that. However, a simple list of lists doesn't slice.
回答2:
just iterate through that list and delete the index which you want to delete.
for example
for sublist in list:
del sublist[index]
回答3:
A slightly twisted version -
index = 2 #Delete column 2
[ (x[0:index] + x[index+1:]) for x in L]
回答4:
You can do it with a list comprehension:
>>> removed = [ l.pop(2) for l in L ]
>>> print L
[['a', 'b', 'd'], [1, 2, 4], ['w', 'x', 'z']]
>>> print removed
['d', 4, 'z']
It loops the list and pops every element in position 2.
You have got list of elements removed and the main list without these elements.
回答5:
This is a very easy way to remove whatever column you want.
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']]
回答6:
L= [['a', 'b', 'C', 'd'], [1, 2, 3, 4], ['w', 'x', 'y', 'z']]
_=[i.remove(i[2])for i in L]
回答7:
If you don't mind on creating new list then you can try the following:
filter_col = lambda lVals, iCol: [[x for i,x in enumerate(row) if i!=iCol] for row in lVals]
filter_out(L, 2)
回答8:
[(x[0], x[1], x[3]) for x in L]
It works fine.
回答9:
An alternative to pop()
:
[x.__delitem__(n) for x in L]
Here n
is the index of the elements to be deleted.
来源:https://stackoverflow.com/questions/13244466/in-python-how-do-i-delete-the-nth-list-item-from-a-list-of-lists-column-delete