[英]Get column from 2D list in Python
I have a 2D list and like to get individual column from the list. 我有一个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_)
If I print column values, I have error as 如果我打印列值,则出现错误
>>>X[:,1]
*** TypeError: list indices must be integers, not tuple
But why the following example works 但是为什么下面的例子起作用
>>> 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])
What is the difference? 有什么区别?
you can change the list to numpy array. 您可以将列表更改为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.