【发布时间】:2021-10-12 05:27:10
【问题描述】:
代码:
import numpy as np
#generate some fake data
x = np.random.random(10)*10
y = np.random.random(10)*10
print(x) #[4.98113477 3.14756425 2.44010373 0.22081256 9.09519374 1.29612129 3.65639393 7.72182208 1.05662368 2.33318726]
col = np.where(x<1,'k',np.where(y<5,'b','r'))
print(col) #['r' 'r' 'r' 'k' 'b' 'b' 'r' 'b' 'r' 'b']
t = []
for i in range(1,10):
t.append(i)
print(t) #[1, 2, 3, 4, 5, 6, 7, 8, 9]
cols = np.where(t % 2 == 0,'b','r')
print(cols)
错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-58-350816096da9> in <module>
6 print(t)
7
----> 8 cols = np.where(t % 2 == 0,'b','r')
9 print(cols)
TypeError: unsupported operand type(s) for %: 'list' and 'int'
我正在尝试生成颜色代码,蓝色表示偶数,红色表示奇数。 为什么我在这里得到错误,而它在第一段代码中工作?
【问题讨论】:
-
t是一个列表(不是 numpy 数组),列表不支持%运算符。如错误消息所述。 -
您需要将
t设为一个numpy 数组,就像第一段代码中的x。