问题
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