Issue
please tell what am I doing wrong here the output is repeated
import numpy as np
hj = np.array([[2, 3, 0], [6, 5, 7], [8, 9, 7], [1, 1, 1]])
print(hj)
print("2-D")
grr = hj
for x in grr:
for y in grr:
print(grr)
I even tried to do hj = np.arange(0, 10).reshape(5, 2)
I also did
import numpy as np
hj = np.array([[2, 3, 0], [6, 5, 7], [8, 9, 7], [1, 1, 1]])
# hj = np.arange(0, 10).reshape(5, 2)
# print(hj)
print("2-D")
for x in hj:
for y in hj:
print(hj)
Solution
In [25]: arr = np.array([[1,2],[3,4]])
Lets look in more detail at what the variables are in the loop:
In [26]: for x in arr:
...: print('%r %r'%(x, arr))
...: for y in x:
...: print('%r %r %r'%(y, x, arr))
...:
array([1, 2]) array([[1, 2], # a (2,) and (2,2) array
[3, 4]])
1 array([1, 2]) array([[1, 2], # a scalar, a (2,) and (2,2)
[3, 4]])
2 array([1, 2]) array([[1, 2],
[3, 4]])
array([3, 4]) array([[1, 2],
[3, 4]])
3 array([3, 4]) array([[1, 2],
[3, 4]])
4 array([3, 4]) array([[1, 2],
[3, 4]])
You could use a double list comprehension to produce a list of lists:
In [27]: [[y for y in x] for x in arr]
Out[27]: [[1, 2], [3, 4]]
In [28]: arr.tolist() # faster
Out[28]: [[1, 2], [3, 4]]
Answered By - hpaulj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.