简体   繁体   中英

How to remove specific elements in nested lists in python

Let's say I got the following array:

array = [[1, 2, 3, 1],
         [4, 5, 6, 4],
         [7, 8, 9, 7], 
         [7, 8, 9, 7]]

I want to remove the first and last list in the array and than the first and last element of the middle lists (return should basically be: [[5, 6], [8, 9]] ).

I tried the following:

array.remove(array[0])
array.remove(array[-1])
for i in array:
     array.remove(i[0])
     array.remove(i[-1])

But I always get ValueError: list.remove(x): x not in list . Why?

Simple way to achive this is to slice the array list using list comprehension expression like:

array = [[1, 2, 3, 1],
         [4, 5, 6, 4],
         [7, 8, 9, 7],
         [7, 8, 9, 7]]

array = [a[1:-1]for a in array[1:-1]]

Final value hold by array will be:

[[5, 6], [8, 9]]

Here array[1:-1] returns the list skipping the first and last element from the array list

You should remove the items from the sublist, not the parent list:

for i in array:
    i.remove(i[0])
    i.remove(i[-1])

You can also remove both items in one line using del :

>>> for i in array:
...    del i[0], i[-1]
>>> array
[[5, 6], [8, 9]]

Using numpy

import numpy as np

array = np.array(array)
array[1:3, 1:3]

return

array([[5, 6],
       [8, 9]])

Or, with <list>.pop :

array = [[1, 2, 3, 1],
         [4, 5, 6, 4],
         [7, 8, 9, 7], 
         [7, 8, 9, 7]]

for i in range(len(array)): # range(len(<list>)) converts 'i' to the list inedx number.
    array[i].pop(0)
    array[i].pop(-1)

To answer your question,

.remove removes the first matching value, not a specific index. Where as .pop removes the it by the index.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM