How to delete a row from a 2D list based on specific column values?

做~自己de王妃 提交于 2020-12-06 12:57:09

问题


For example we have this 2D list:

list1 = [['tom',67,'engineer',2],
     ['ron',42,'scientist',4],
      ['alie',56,'doctor',3],
      ['rambo',29,'lawyer',7]]

Now I have to delete rows in which column 4 has odd values. Is there any way in python3 to do this using pop or something else?


回答1:


The easiest way it to create a new list from list1. You can assign this to list1 if you wish to replace it. You can use:

list2 = [v for v in list1 if v[3] % 2 == 0]

In your example, list2 gets the following value:

[['tom', 67, 'engineer', 2],
 ['ron', 42, 'scientist', 4]]

If you just want to replace list1 with the new list, you can do so directly:

list1 = [v for v in list1 if v[3] % 2 == 0]

If you need to preserve references to list1, you can change the existing list with:

list1[:] = [v for v in list1 if v[3] % 2 == 0]



回答2:


The solution with using remove. It's easy to understand you.

for value in list1[:]:
    if value[3] % 2 != 0:
        list1.remove(value)

Result

[['tom', 67, 'engineer', 2], ['ron', 42, 'scientist', 4]]


来源:https://stackoverflow.com/questions/37904343/how-to-delete-a-row-from-a-2d-list-based-on-specific-column-values

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