【问题标题】:Why am I getting a type error for the second pice of code while the first on worked?为什么我在第一段代码工作时收到第二段代码的类型错误?
【发布时间】: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

标签: python numpy types


【解决方案1】:

您的代码 sn-p 中的“第一次”,xy 是 numpy 数组,由对 np.random.random 的调用创建:

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

t 不是这种情况。正如一些 cmets 所指出的,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'

但是,您可以按照 Barmar 的指示将 mod 运算符应用于 numpy 数组:

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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 2018-07-05
    • 2017-06-28
    • 2021-09-30
    • 2020-09-08
    • 1970-01-01
    相关资源
    最近更新 更多