10 python
我遇到了问题.我有一个由31个元素组成的数组,称为颜色.我还有另一个数组,其整数在0到31之间变化,这称为c.我想生成一个新数组,其中c中的值现在是颜色中的相应值.
我写:
newarray =颜色并[c]
但得到错误消息"列表索引必须是整数",但c是一个整数数组.我是python的新手,没有时间做教程,因为我只需要它来进行特定的绘图任务.有人能帮我一把吗?
谢谢
Dou*_*der 18
整数数组!=整数
list indices必须是整数 - 你已经给出了一个整数列表.
你可能想要一个列表理解:
newarray = [ colors[i] for i in c ]
Run Code Online (Sandbox Code Playgroud)
编辑:
如果你仍然得到相同的错误,那么你的断言c是一个整数列表是不正确的.
请试试:
print type(c)
print type(c[0])
print type(colors)
print type(colors[0])
Run Code Online (Sandbox Code Playgroud)
然后我们可以找出你得到的类型.另外一个简短但完整的例子会有所帮助,并且可能会教你很多关于你的问题.
EDIT2:
因此,如果c实际上是一个字符串列表,你应该提到这一点,字符串不会自动转换为整数,这与其他一些脚本语言不同.
newarray = [ colors[int(i)] for i in c ]
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
a)colors需要长达32个条目.b)i列表推导中c()的元素需要转换为整数(int(i)).
| 归档时间: |
|
| 查看次数: |
80332 次 |
| 最近记录: |