In Python, how do I delete the Nth list item from a list of lists (column delete)?

試著忘記壹切 提交于 2019-12-01 03:11:45

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.

just iterate through that list and delete the index which you want to delete.

for example

for sublist in list:
    del sublist[index]

A slightly twisted version -

index = 2  #Delete column 2 
[ (x[0:index] + x[index+1:])  for x in L]

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.

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']]
       L= [['a', 'b', 'C', 'd'], [1, 2, 3, 4], ['w', 'x', 'y', 'z']]

       _=[i.remove(i[2])for i in L]

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)
ParaMeterz
[(x[0], x[1], x[3]) for x in L]

It works fine.

An alternative to pop():

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!