Python打印错误:%d格式:需要数字,而不是元组

Python打印错误:%d格式:需要数字,而不是元组,python,numpy,ipython,typeerror,Python,Numpy,Ipython,Typeerror,我尝试打印时出现意外错误: 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:

我尝试打印时出现意外错误:

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("{} {}".format(i, a[i]))
如果确实需要索引和元素,可以使用
enumerate

for i, x in enumerate(np.nditer(a)):
    print("{} {}".format(i, x))
而且,顾名思义,
multi_index
,不是整数


i
不是一个数字

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

请改用
i[0]

您正在使用它。返回索引元组的多索引

由于数组是1D,请将
i=it.multi_index
替换为要提取的索引

对你来说,应该是这样
i=it。多索引[0]
i
属于
tuple
类型,请使用
it。多索引[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()

请尝试打印(repr((i,a[i]))此处无需打印-will doThank you@cricket_007,非常有用!将
enumerate
nditer
一起使用是毫无意义的-无论如何,您已经在
it[0]
中拥有了值。如果您确实希望始终使用1d索引,请使用
for。。。在np.ndenumerate(a.flat)
和drop
nditer
entirelyWell中,当然可以。我不太熟悉numpy api