繁体   English   中英

从Python的2D列表中获取列

[英]Get column from 2D list in Python

我有一个2D列表,喜欢从列表中获取单个列。

          X=[]
          for line in lines:
             c,xmin,ymin,xmax,ymax = line.split(' ')
             xmin_ = float(xmin)
             ymin_ = float(ymin)
             xmax_ = float(xmax)
             ymax_ = float(ymax)
             area_ = (xmax_ - xmin_)*(ymax_ - ymin_)
             X.append(xmax_-xmin_, ymax_-ymin_, area_)

如果我打印列值,则出现错误

>>>X[:,1]

*** TypeError: list indices must be integers, not tuple

但是为什么下面的例子起作用

>>> a = arange(20).reshape(4,5)

>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

>>> a[:, 1]
array([ 1,  6, 11, 16])

有什么区别?

您可以将列表更改为numpy数组。

import numpy as np
x=[[1,2,3],[4,5,6]]
x[:,1]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: list indices must be integers, not tuple
xa = np.array(x)
xa
array([[1, 2, 3],
       [4, 5, 6]])
xa[:,1]
array([2, 5])

暂无
暂无

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

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