首页 > 解决方案 > 为什么在第一个代码有效时,第二个代码会出现类型错误?

问题描述

代码:

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'

我正在尝试生成颜色代码,蓝色表示偶数,红色表示奇数。为什么我会在这里收到错误,而它在第一段代码中起作用?

标签: pythonnumpytypes

解决方案


您的代码片段中的“第一次”,x并且y是 numpy 数组,由对以下的调用创建np.random.random

col = np.where(x<1,'k',np.where(y<5,'b','r'))

情况并非如此t。正如一些评论所指出的,t是一个通用的 Python 列表。您不能将 mod 运算符应用于 Python 列表。

>>> [1, 2, 3, 4] % 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'list' and 'int'

但是,您可以将 mod 运算符应用于 numpy 数组,如 Barmar 所示:

t = np.array([2,3,4,5])
t % 2 
# returns array([0, 1, 0, 1])

np.where(t % 2 == 0, 'a', 'b')
# returns array(['a', 'b', 'a', 'b'], dtype='<U1')

推荐阅读