[英]TypeError: List indices must be integer must be integer, not tuple
I am trying to find first_row = [1, 2, 3, 4, ...]
我试图找到first_row = [1, 2, 3, 4, ...]
Currently, I have list = [[1, a], [2, b], [3, c], [4, d], ...]
目前,我有list = [[1, a], [2, b], [3, c], [4, d], ...]
and tried running: list[:, 0]
并尝试运行: list[:, 0]
Output error: TypeError: List indices must be integer must be integer, not tuple
输出错误:类型错误: TypeError: List indices must be integer must be integer, not tuple
list
doesn't support multiple (ie "comma-separated") indices, so you need something like list
不支持多个(即“逗号分隔”)索引,因此您需要类似
[sublist[0] for sublist in list]
The most popular alternative supporting multiple indexing like you tried is numpy
's multidimensional array最流行的支持多索引的替代方法是numpy
的多维数组
The reason why list
cannot do this is because it is a general container, so it cannot imply what you store inside. list
之所以不能这样做,是因为它是一个通用的容器,所以它不能暗示你在里面存储了什么。 You might have你可能有
values = [[1, 2], 'three', MyClass(4, 5, 6), None]
Applying [0, :]
to this would make no sense, the same way as it doesn't in most cases.将[0, :]
应用于此毫无意义,就像在大多数情况下一样。
The subscript lst[:,0]
does not do what you think it does.下标lst[:,0]
没有做你认为的那样。 You might be used to pandas or other libraries which support indexing in multidimensional matrices, but the builtin list
does not support this.您可能习惯了Pandas或其他支持多维矩阵索引的库,但内置list
不支持这一点。
Instead, you should use a list-comprehension.相反,您应该使用列表理解。
first_row = [column[0] for column in lst]
This is a shorthand for the following more verbose expression.这是以下更详细的表达式的简写。
first_row = []
for column in lst:
first_row.append(lst[0])
In other words, you cannot vectorize multi-indexing with the list
type.换句话说,您不能使用list
类型对多索引进行矢量化。 You have to recover each column one by one and the first element of each of those independently.您必须一一恢复每一列,并独立恢复每列的第一个元素。
As a sidenote, try avoiding calling you variables list
as it shadows the builtin of the same name.作为旁注,请尽量避免调用变量list
因为它会隐藏同名的内置函数。
first_row = [i[0] for i in list]
Edit: Since there are already two answers as this one, let me show a different one if you want to use slicing.编辑:由于已经有两个答案作为这个答案,如果您想使用切片,让我展示一个不同的答案。 First of all you SHOULDN'T use list as the name of your variable, since list is a reserved word in python.首先,您不应该使用 list 作为变量的名称,因为 list 是 python 中的保留字。 Suppose your list is called list1, you can do:假设您的列表名为 list1,您可以执行以下操作:
first_row = list(np.array(list1)[0,:].astype(int))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.