python - 为什么Python中的.format方法需要显式字符串转换?

标签 python numpy

以下代码给出 TypeError。

from sklearn.model_selection import KFold
kf = KFold(n_splits=5,shuffle=False).split(range(25))

print('{} {:^61} {}'.format('Iteration','Training set observations','Testing set observations'))
for iteration, data in enumerate(kf, start=3):
    print('{:^9} {} {:^25}'.format(iteration, data[0], data[1]))

TypeError: unsupported format string passed to numpy.ndarray.format

当我们使用str(data[1])时,代码给出了正确的输出

为什么需要这种显式字符串转换?

最佳答案

来自,例如 https://docs.python.org/3.4/library/string.html#format-specification-mini-language :

A general convention is that an empty format string ("") produces the same result as if you had called str() on the value. A non-empty format string typically modifies the result.

因此,当 :^25data[1] 匹配时,它会调用 data 的 __format__() 方法[1] 对象,它是一个 numpy.ndarray。这些对象遵循 Python 的 list 行为,即在格式字符串非空时引发 TypeError。空格式字符串会导致在 data[0] (在您的示例中)上调用 str() ,这样就可以工作。非空格式字符串(即 data[1]:^25)在 Python 中的列表上失败,因为 Python 中的标准列表可能是异构对象的集合因此单一格式规范可能不适用于像这样的列表:[1, 2.3, 'four']numpy 只是遵循相同的约定。

<小时/>

另请参阅https://github.com/numpy/numpy/issues/5543针对 numpyGitHub 页面上的未决问题。该问题似乎与您在帖子中提到的同一问题有关。

关于python - 为什么Python中的.format方法需要显式字符串转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52585752/

相关文章:

python - BeautifulSoup- find_all- 订单保存

Python:安装和使用 Exscript 模块 Windows x86

python - 覆盖 get_object() 并手动设置 PK

python - 如何在 Python 中绘制最大似然估计

python - 在 Python 中插值 3d 数组扩展

python - Numpy 数组索引超出遗传算法范围

python - 有没有办法使用python进一步缩短稀疏解决时间?

python - openid 和 oauth 一起?

python - 保存 32 位浮点 TIFF 图像

如果其他列为假, Pandas : dataframe cumsum , 将重置