【问题标题】:Use numpy array as arguments for print()使用 numpy 数组作为 print() 的参数
【发布时间】:2018-11-01 15:43:55
【问题描述】:

我在一个非常简单的事情上苦苦挣扎。

我想打印一个特定格式的字符串:

import numpy as np
array = np.array([123.456789, 1.23456, 12.3456])
print("My First number is %3.4f, second %1.2f and third %2.9f" % array)

"array" 是一个 numpy 数组,包含我想打印的参数 (size: (1,3))。但我收到以下错误消息:

TypeError:只有 size-1 的数组可以转换为 Python 标量

这很好用

array = (123.456789, 1.23456, 12.3456)
print("My First number is %3.4f, second %1.2f and third %2.9f" % array)

但我的数据确实是一个 numpy 数组。有没有一种简单的方法可以将数组转换为将值用作格式化打印 pint() 的参数?

【问题讨论】:

  • array = tuple(array) 添加这个。

标签: python arrays numpy


【解决方案1】:

传递给元组:

print("My First number is %3.4f, second %1.2f and third %2.9f" % tuple(array))

或使用new format

array = np.array([123.456789, 1.23456, 12.3456])
print("My First number is {:3.4f}, second {:1.2f} and third {:2.9f}".format(*array))
>> My First number is 123.4568, second 1.23 and third 12.345600000

【讨论】:

  • 非常感谢! “新格式”最符合我的要求。
【解决方案2】:

如果有多个项目要格式化成字符串,% 格式化程序需要一个元组,这应该修复它

 print("My First number is %3.4f, second %1.2f and third %2.9f" % (array[0],array[1],array[2]))

【讨论】:

    【解决方案3】:

    它不起作用,因为两者不是同一个对象。 也就是说第一个数组是numpy.ndarray

    第二个有效的数组是元组。

    所以

    为了运行第一个 numpy.ndarray,请尝试以下行

    array1 = np.array([123.456789, 1.23456, 12.3456])

    print("我的第一个数字是 %3.4f,第二个是 %1.2f,第三个是 %2.9f" , array1[0], array1[1],array1[2])

    【讨论】:

      猜你喜欢
      • 2019-12-02
      • 1970-01-01
      • 2017-12-20
      • 2022-01-26
      • 1970-01-01
      • 2015-10-17
      • 2016-08-29
      • 2018-07-08
      • 1970-01-01
      相关资源
      最近更新 更多