简体   繁体   English

复制和过滤嵌套列表Python

[英]Copy and Filter nested list Python

I have a list of lists that looks something like: 我有一个看起来像这样的列表列表:

[[51502 2 0 ... 0 1 1]
 [8046 2 0 ... 1 1 2]
 ....
 [40701 1 1 ... 1 1 1]]

In my case, every first element in the nested list is "out-of-place" and I want to remove all of them. 就我而言,嵌套列表中的每个第一个元素都是“不适当的”,我想删除所有它们。

# My goal: 
[[2 2 0 ... 0 1 1]
 [2 0 ... 1 1 2]
 ....
 [1 1 ... 1 1 1]]

I've tried np.delete(the_nested[i],0) using for-loop and it gave me the error of " could not broadcast input array " 我已经尝试过使用for循环np.delete(the_nested[i],0) ,它给了我“ 无法广播输入数组 ”的错误

I've also tried to delete it manually using del and pop , but as expected, numpy didn't allow it since static. 我也尝试过使用delpop手动将其del ,但是正如预期的那样,自从静态以来,numpy不允许这样做。

Could anyone provide an alternative solution? 谁能提供替代解决方案?

Update: Type for the_nested is numpy.ndarray 更新:the_nested的类型为numpy.ndarray

Note: I'm sorry beforehand if this post turns out to be a duplicate (hopefully not!) :( 注意:如果这篇文章被发现是重复的,我很抱歉(希望不是!):(

I think you can just index it out: 我认为您可以将其编入索引:

np.array(the_nested)[:,1:]

In your case: 在您的情况下:

the_nested = [[51502, 2, 0,  0, 1, 1],
              [8046 ,2 ,0 , 1 ,1 ,2],
              [40701, 1 ,1  ,1 ,1 ,1]]

>>> np.array(the_nested)[:,1:]
array([[2, 0, 0, 1, 1],
       [2, 0, 1, 1, 2],
       [1, 1, 1, 1, 1]])

Alternatively, with np.delete (no loop needed): 或者,使用np.delete (无需循环):

>>> np.delete(np.array(the_nested),0,axis=1)
array([[2, 0, 0, 1, 1],
       [2, 0, 1, 1, 2],
       [1, 1, 1, 1, 1]])

I see you have a list and if you don't want to use additional packages like numpy you can do something like this. 我看到您有一个列表,如果您不想使用numpy类的其他软件包,则可以执行以下操作。 But it involve looping. 但这涉及循环。 Also, it is not modifying the original list. 另外,它不会修改原始列表。

the_nested = [[51502, 2, 0,  0, 1, 1],
              [8046 ,2 ,0 , 1 ,1 ,2],
              [40701, 1 ,1  ,1 ,1 ,1]]

res = []

_ = [res.append(x[1:]) for x in the_nested]

# Output : 
[[2, 0, 0, 1, 1], [2, 0, 1, 1, 2], [1, 1, 1, 1, 1]] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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