python - 为什么在第一个代码有效时,第二个代码会出现类型错误?
问题描述
代码:
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'
我正在尝试生成颜色代码,蓝色表示偶数,红色表示奇数。为什么我会在这里收到错误,而它在第一段代码中起作用?
解决方案
您的代码片段中的“第一次”,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')
推荐阅读
- python - ModuleNotFoundError:没有名为“__main__.web_app”的模块;从子文件夹导入包时,'__main__' 不是包
- css - CSS红色方块在顶部
- android - JSONObject 无法在 Volley 中转换为 JSONArray
- sql - Oracle REF 数据类型
- macos - 在 Mac OS 的终端或 iterm2 应用程序上显示泰卢固语
- javascript - 如何保持选择选项的值是动态的?
- python - 如何停用鼠标运动(
) 在我拖动无框窗口时在 Windows 任务栏上? - java - 使用 docx4j 将可见背景图片设置为 docx 文档
- vb.net - 以给定的时间间隔获取两个日期之间的所有时间
- blockchain - 通过 rpc 从 Remix 连接到本地区块链时出错