【问题标题】:Python print error: %d format: a number is required, not tuplePython 打印错误:%d 格式:需要一个数字,而不是元组
【发布时间】:2017-12-28 14:14:27
【问题描述】:

我在尝试打印时遇到意外错误:

import numpy as np
a = np.array([11, 21, 31, 41, 51])
it = np.nditer(a, flags=['multi_index'], op_flags=['readwrite'])

while not it.finished:
    i = it.multi_index
    print("%d %d" % (i, a[i]))
    it.iternext()

此代码生成错误:

TypeError: %d format: a number is required, not tuple

但是当我这样做时:

for i in xrange(5):
    print("%d %d" % (i, a[i]))

然后我得到了预期的结果:

0 11
1 21
2 31
3 41
4 51

那么为什么在前面的情况下会出现这个错误?

【问题讨论】:

  • 试试print(repr((i, a[i])))
  • 这里不需要nditer - ndindex 可以

标签: python numpy ipython typeerror


【解决方案1】:

你应该尝试使用新的样式格式

print("{} {}".format(i, a[i]))

如果你真的想要索引和元素,可以使用enumerate

for i, x in enumerate(np.nditer(a)):
    print("{} {}".format(i, x))

而且,顾名思义,multi_index 不是整数。

https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html

【讨论】:

  • 谢谢@cricket_007,非常有帮助!
  • enumeratenditer 一起使用是没有意义的——无论如何,您已经拥有it[0] 的价值。如果您实际上总是想要一维索引,请使用 for ... in np.ndenumerate(a.flat) 并完全删除 nditer
  • 嗯,当然。我对 numpy api 不是很熟悉
【解决方案2】:

i 不是数字。

In [69]: it.multi_index
Out[69]: (0,)

请改用i[0]

【讨论】:

    【解决方案3】:

    您正在使用 it.multi_index 返回一个索引元组。

    由于您的数组是一维数组,请将i=it.multi_index 替换为您要提取的索引。

    在你的情况下,它应该是 i=it.multi_index[0]

    【讨论】:

      【解决方案4】:

      ituple 类型,使用it.multi_index[0] 获取第一个元素,如下所示:

      while not it.finished:
          i = it.multi_index[0]
          print("%d %d" % (i, a[i]))  # The better is using "{} {}".format(i, a[i])
          it.iternext()
      

      【讨论】:

        猜你喜欢
        • 2015-01-31
        • 2020-09-24
        • 2015-02-04
        • 2015-12-20
        • 1970-01-01
        • 1970-01-01
        • 2015-07-22
        • 2017-11-17
        • 1970-01-01
        相关资源
        最近更新 更多