[英]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]]
). 我想删除数组中的第一个和最后一个列表,而不是中间列表中的第一个和最后一个元素(返回应该基本上是:
[[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
. 但是我总是得到
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
列表进行切片,例如:
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: array
保留的最终值将是:
[[5, 6], [8, 9]]
Here array[1:-1]
returns the list skipping the first and last element from the array
list 在这里,
array[1:-1]
返回列表,跳过array
列表中的第一个和最后一个元素
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
: 您还可以使用
del
在一行中删除这两项:
>>> for i in array:
... del i[0], i[-1]
>>> array
[[5, 6], [8, 9]]
Using numpy 使用numpy
import numpy as np
array = np.array(array)
array[1:3, 1:3]
return 返回
array([[5, 6],
[8, 9]])
Or, with <list>.pop
: 或者,使用
<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. .remove
删除第一个匹配值,而不是特定的索引。 Where as .pop
removes the it by the index. 其中as
.pop
通过索引将其删除。
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.