python - numpy fromstring 不推荐使用 frombuffer 代替
问题描述
在 Python 代码中使用 numpy 1.18.1
` def printBoard(self): current = self.player other = self.player % 2 + 1
currBin = '{:049b}'.format(self.current_position)
currRev = currBin[::-1]
cArr = (np.fromstring(currRev,'u1') - ord('0'))*current
other_position = self.current_position^self.mask
othBin = '{:049b}'.format(other_position)
othRev = othBin[::-1]
oArr = (np.fromstring(othRev,'u1') - ord('0'))*other
tArr = oArr+cArr
brd = np.reshape(tArr,(7,7),order = 'F')
for y in range(bitBoard.HEIGHT,-1,-1):
for x in range(bitBoard.WIDTH):
print(brd[y,x],end = ' ')
print()
print()
`
该行:
cArr = (np.fromstring(currRev,'u1') - ord('0'))*current
给出以下警告:
DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
cArr = (np.fromstring(currRev,'u1') - ord('0'))*current
将 'fromstring' 替换为 'frombuffer' 会出现以下错误:
cArr = (np.frombuffer(currRev,'u1') - ord('0'))*current
TypeError: a bytes-like object is required, not 'str'
尽管进行了一些谷歌搜索,但我找不到我应该使用的东西。有人可以帮忙吗?
谢谢你。
艾伦
解决方案
您的代码的相关部分是产生currRev
. 由此我可以构建这个例子:
In [751]: astr = '{:049b}'.format(123)[::-1]
In [752]: astr
Out[752]: '1101111000000000000000000000000000000000000000000'
你的警告:
In [753]: np.fromstring(astr, 'u1')
/usr/local/bin/ipython3:1: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
#!/usr/bin/python3
Out[753]:
array([49, 49, 48, 49, 49, 49, 49, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48],
dtype=uint8)
frombuffer
想要一个字节串,所以让我们创建一个:
In [754]: astr.encode()
Out[754]: b'1101111000000000000000000000000000000000000000000'
In [755]: np.frombuffer(astr.encode(),'u1')
Out[755]:
array([49, 49, 48, 49, 49, 49, 49, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48],
dtype=uint8)
该行的其余部分:
In [756]: _-ord('0')
Out[756]:
array([1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0], dtype=uint8)
获得相同数组的另一种方法:
In [758]: np.array(list(astr),'uint8')
Out[758]:
array([1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0], dtype=uint8)
推荐阅读
- actionscript-3 - 如何根据动态文本的宽度创建动态下三分之一 i AS3
- playwright - Playwright 测试运行器:将测试限制为仅一个浏览器,其配置文件包含许多项目
- css - 打字机效果全幅
- jenkins - Jenkins 错误:在构建时找不到名为 toolbelt 的工具
- api - 是否有任何选项可以通过 PushBullet API 获取最后传入的短信?
- javascript - 如何从 JS 文件中的 groovy 控制器访问返回的对象
- selenium - XPATH 文本设置基于语言的动态值
- mysql - 在 Apache Superset SQL LAB 中计算同比增长时在查询中添加过滤器列
- python - 如何使用 Python 排序函数使用布尔比较函数对列表进行排序
- autocomplete - 当我按下分号和空格时,如何禁用自动完成弹出;