在Python中的列表中的每个(列表)元素中切掉第一个元素

Hor*_*ith 1 python numpy list slice

说我们有一个清单:

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)

然后我想通过切掉列表中每个元素中的第一个元素来创建一个新列表:

b = a[][1:]
Run Code Online (Sandbox Code Playgroud)

显然上面的内容不起作用,但我现在想要的是:

[[2, 3], [5, 6], [8, 9]]
Run Code Online (Sandbox Code Playgroud)

当然我可以循环使用它,但我想知道的是,是否有可能以任何类似的方式执行它,而不是我在上面做错了.另外,最好有一个更好/更好的方法来做这个numpy,在这种情况下,它不需要通过切片我尝试这样做的方式完成?

kar*_*ikr 6

您可以使用列表推导:

b = [x[1:] for x in a]
Run Code Online (Sandbox Code Playgroud)

演示:

>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> b = [x[1:] for x in a]
>>> b
[[2, 3], [5, 6], [8, 9]]
>>>
Run Code Online (Sandbox Code Playgroud)


bco*_*ins 5

使用numpy索引/切片表示法,您可以使用逗号分隔每个维度的切片:

import numpy as np
a = np.array([[1,2,3],[1,2,3],[1,2,3]])
print a[:,1:]
Run Code Online (Sandbox Code Playgroud)

输出:

[[2 3]
 [2 3]
 [2 3]]
Run Code Online (Sandbox Code Playgroud)

有关numpy索引的其他阅读:http: //docs.scipy.org/doc/numpy/reference/arrays.indexing.html