yon*_*oni 1 python slice python-3.x
我正在尝试做我认为应该简单的事情:
我制作了一个2D列表:
a = [[1,5],[2,6],[3,7]]
Run Code Online (Sandbox Code Playgroud)
我想滑出第一个column
并尝试:
1)
a[:,0]
...
TypeError: list indices must be integers or slices, not tuple
Run Code Online (Sandbox Code Playgroud)
2)
a[:,0:1]
...
TypeError: list indices must be integers or slices, not tuple
Run Code Online (Sandbox Code Playgroud)
3)
a[:][0]
[1, 5]
Run Code Online (Sandbox Code Playgroud)
4)
a[0][:]
[1, 5]
Run Code Online (Sandbox Code Playgroud)
5)得到它,但这是这样做的方式吗?
aa[0] for aa in a
Run Code Online (Sandbox Code Playgroud)
使用numpy
它很容易,但Python的方式是什么?
2D切片a[:, 0]
只适用于NumPy数组,不适用于列表.
但是,您可以使用转置(行成为列,反之亦然)嵌套列表zip(*a)
.转置后,只需切出第一行:
a = [[1,5],[2,6],[3,7]]
print zip(*a) # [(1, 2, 3), (5, 6, 7)]
print list(zip(*a)[0]) # [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
72 次 |
最近记录: |