gpt4 book ai didi

python - 如何进行二维切片?

转载 作者:太空宇宙 更新时间:2023-11-04 08:43:20 26 4
gpt4 key购买 nike

我正在尝试做我认为应该很简单的事情:

我制作了一个二维列表:

a = [[1,5],[2,6],[3,7]]

我想滑出第一个 column 并尝试:

1)

a[:,0]
...
TypeError: list indices must be integers or slices, not tuple

2)

a[:,0:1]
...
TypeError: list indices must be integers or slices, not tuple

3)

a[:][0]
[1, 5]

4)

a[0][:]
[1, 5]

5) 明白了,但这是这样做的方法吗?

 aa[0] for aa in a

使用 numpy 会很容易,但是 Python 的方式是什么?

最佳答案

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]

关于python - 如何进行二维切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42945064/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com