首页 > 解决方案 > 如何解决 TypeError 的问题:传递给 numpy.ndarray.__format__ 的格式字符串不受支持

问题描述

我有以下代码,但输出给我一个错误。

possible_rolls = arr = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
roll_result = np.random.choice(possible_rolls,1,replace=True)
modified_result = roll_result + 11
action_succeeded = modified_result > 15

print("On a modified roll of {:d}, Alice's action {}.".format(modified_result, "succeeded" if action_succeeded else "failed"))

TypeError:传递给 numpy.ndarray 的格式字符串不受支持。格式

标签: pythonpandasnumpy

解决方案


那是因为modified_result是一个数组,而不是一个数字:

possible_rolls = arr = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
roll_result = np.random.choice(possible_rolls,1,replace=True)
modified_result = roll_result + 11
action_succeeded = modified_result > 15

print(type(modified_result))
>>> <class 'numpy.ndarray'>

这将解决问题:

print("On a modified roll of {:d}, Alice's action {}.".format(modified_result[0], "succeeded" if action_succeeded else "failed"))

>>> On a modified roll of 13, Alice's action failed.

推荐阅读