np.nditer()

我直接写在了代码里:

#单数组的迭代
# import numpy as np
# a = np.arange(6).reshape(2,3)
# print a
# for x in np.nditer(a):
#     print x
# print a.T

#you will find a & a.T has the same result
# for x in np.nditer(a.T):
#     print x
# print a.T.copy()
# for x in np.nditer(a.T.copy(order='C')):
#     print x
#

#默认是只读对象的,你需要修改的时候指定read-write
# for x in np.nditer(a,op_flags=['readwrite']):
#     x[...]=2*x
#
# print a
#
#将一维的最内层的循环转移到外部的循环迭代器,使得numpy的矢量化操作在处理更大规模数据时变得更有效率
# import numpy as np
# a=np.arange(6).reshape(3,2)
# for x in np.nditer(a,flags=['external_loop']):
#     print x
# for x in np.nditer(a,flags=['external_loop'],order='F'):
#     print x

#跟踪单个索引和多种索引
import numpy as np
a=np.arange(6).reshape(2,3)
print a
it=np.nditer(a,flags=['c_index'])
while not it.finished:
    print "%d <%d>" % (it[0],it.index)
    it.iternext()

print "*****************"

itit=np.nditer(a,flags=['f_index'])
while not itit.finished:
    print "%d <%d>" % (itit[0],itit.index)
    itit.iternext()

print "*****************"
ititit=np.nditer(a,flags=['multi_index'])
while not ititit.finished:
    print "%d <%s>" % (ititit[0],ititit.multi_index)
    ititit.iternext()


可以运行结果看看!

第一个import numpy as np的结果:

[[0 1 2]
 [3 4 5]]
0
1
2
3
4
5
[[0 3]
 [1 4]
 [2 5]]
0
1
2
3
4
5
[[0 3]
 [1 4]
 [2 5]]
0
3
1
4
2
5
[[ 0  2  4]
 [ 6  8 10]]

第二个import numpy as np 的结果:

[0 1 2 3 4 5]
[0 2 4]
[1 3 5]

第三个import numpy as np的结果:

[[0 1 2]
 [3 4 5]]
0 <0>
1 <1>
2 <2>
3 <3>
4 <4>
5 <5>
*****************
0 <0>
1 <2>
2 <4>
3 <1>
4 <3>
5 <5>
*****************
0 <(0, 0)>
1 <(0, 1)>
2 <(0, 2)>
3 <(1, 0)>
4 <(1, 1)>
5 <(1, 2)>




猜你喜欢

转载自blog.csdn.net/m0_37393514/article/details/79563776
np