TypeError:尝试更改数组列表的某些元素时,列表索引必须是整数,而不是元组 [英] TypeError: list indices must be integers, not tuple when trying to alter certain elements of a list of arrays
问题描述
我有一个x和y坐标的2×n数组的列表.
I have a list of 2 by n arrays of x and y coordinates.
old: [array([[1, 2, 3], [4, 5, 6]]), array([[10, 20, 30], [40, 50, 60]])]
我正在尝试将y坐标(每个数组的第二行)移动某个值'shift'.但是,当我尝试通过以下方法执行此操作时,出现错误:
I am trying to shift the y-coordinates, the second row of each array, by a certain value 'shift'. However, when I try to do this by the method below, I get the an error:
"TypeError:尝试更改数组列表的某些元素时,列表索引必须是整数,而不是元组."
"TypeError: list indices must be integers, not tuple when trying to alter certain elements of a list of arrays."
import pylab
def shiftY(old,shift):
new = list([])
for i in arange(len(old)):
y = old[i][1,:] + shift
newItem = array([old[:,0],y])
new.append(newItem)
return new
old = list()
old.append(arr
ay([[1, 2, 3], [4, 5, 6]]))
old.append(array([[10,20,30],[40,50,60]]))
shift =3
new=shiftY(old,shift)
print(new)
跟踪:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27_32bit\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "C:/Users/tald574/testShifty.py", line 25, in <module>
new=shiftY(old,shift)
File "C:/Users/tald574/testShifty.py", line 15, in shiftY
newItem = array([old[:,0],y])
TypeError: list indices must be integers, not tuple
我看不到我在做错什么,因为 newItem
甚至都不应该是列表,它应该是2D数组.如果有人可以告诉我我做错了什么以及如何解决它,将不胜感激.
I can't see what I am doing wrong as newItem
is not even supposed to be a list, it should be a 2D array. Would appreciate it if someone can tell me what I do wrong an how to fix it.
谢谢.
该测试的预期结果将是
new:[array([[1, 2, 3], [7, 8, 9]]), array([[10, 20, 30], [43, 53, 63]])]
推荐答案
列表切片表示法中不需要逗号. array [:,i]
被解析为 array [:t]
,其中 t =,i
是一个元组.有关列表切片的摘要,请参见此处.
You don't need the commas in the list slicing notation. array[:,i]
is parsed as array[:t]
, where t = ,i
is a tuple. See here for a rundown of list slicing.
组是由以下定义逗号,而不是括号.
根据您的情况,替换行
y = old[i][1,:] + shift
newItem = array([old[:,0],y])
使用
y = old[i][1:] + shift
newItem = array([old[:0],y])
这篇关于TypeError:尝试更改数组列表的某些元素时,列表索引必须是整数,而不是元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!