python错误“列表索引必须是整数”,它们是整数

时间:2009-09-21 10:39:26

标签: python

我遇到了问题。我有一个由31个元素组成的数组,称为颜色。我还有另一个数组,其整数在0到31之间变化,这称为c。我想生成一个新数组,其中c中的值现在是颜色中的相应值。

我写道:

  
    

newarray =颜色并[c]

  

但是得到错误消息“list indices必须是整数”,但c是一个整数数组。 我是python的新手,没有时间做教程,因为我只需要它来进行特定的绘图任务。谁能帮我一把?

由于

5 个答案:

答案 0 :(得分:18)

整数数组!=整数

列表索引必须是整数 - 您已经给出了整数列表。

你可能想要列表理解:

newarray = [ colors[i] for i in c ]

编辑:

如果您仍然收到相同的错误,那么c是一个整数列表的断言是不正确的。

请尝试:

print type(c)
print type(c[0])
print type(colors)
print type(colors[0])

然后我们可以找出你得到的类型。另外一个short but complete example会有所帮助,可能会教你很多关于你的问题。

EDIT2:

因此,如果c实际上是字符串列表,您可能应该已经提到过,字符串不会自动转换为整数,与其他一些脚本语言不同。

newarray = [ colors[int(i)] for i in c ]

EDIT3:

以下是一些演示了几个错误修复的最小代码:

x=["1\t2\t3","4\t5\t6","1\t2\t0","1\t2\t31"]
a=[y.split('\t')[0] for y in x]
b=[y.split('\t')[1] for y in x]
c=[y.split('\t')[2] for y in x]  # this line is probably the problem
colors=['#FFFF00']*32
newarray=[colors[int(i)] for i in c]
print newarray

a)colors需要32个条目。  b)列表推导中c(i)的元素需要转换为整数(int(i))。

答案 1 :(得分:2)

这是您的代码:(来自您的评论)

from pylab import* 
f=open("transformdata.txt") 
x=f.readlines() 
a=[y.split('\t')[0] for y in x] 
b=[y.split('\t')[1] for y in x] 
c=[y.split('\t')[2] for y in x]  # this line is probably the problem
subplot(111,projection="hammer") 
colors=['#FFFF00']*31
newarray=[colors [i] for i in c] 
p=plot([a],[b],"o",mfc=color) show()

如果不确切知道您的数据是什么,或者您想要完成什么,我建议您尝试这样做:

c=[int(y.split('\t')[2]) for y in x] 

答案 2 :(得分:1)

Python不支持任意列表索引。您可以使用单个整数索引,如c [4]或切片,如c [4:10]。 SciPy库具有更丰富的索引功能。或者只使用列表推导作为Douglas Leeder的建议。

答案 3 :(得分:1)

好的,我想我知道你在追求什么......

所以你有31种颜色的列表。比如参数,它是一个包含31个字符串的列表...

colours = [ "Black", "DarkBlue", "DarkGreen", ... "White" ]

'c'是0到31范围内的数字数组,但是按随机顺序......

import random
c = [x for x in xrange(32)]
random.shuffle(c)
# 'c' now has numbers 0 to 31 in random order
# c = [ 2, 31, 0, ... 1]

你想要做的是将c中的值作为索引映射到颜色列表中,这样你最终会得到一个颜色列表,并按照c的顺序排列......

mapped = [color[idx] for idx in c]
# mapped has the colors in the same order as indexed by 'c'
# mapped = ["DarkGreen", "White", "Black", ... "DarkBlue"]

如果那不是您想要的,那么您需要修改您的问题!

我认为你有一个基本问题,你的颜色列表中应该有32个元素(颜色),而不是31,如果列表'c'是0到31范围内所有数字的随机混乱(你看,这是32个数字。)

答案 4 :(得分:0)

如果颜色也是integer s或float s,使用Numpy可以更轻松地修复:

import numpy as np
newarray = np.array(colors)[c]
相关问题