Why does python think my array is 0-d? (TypeError: iteration over a 0-d array) [duplicate]

时间秒杀一切 提交于 2021-01-28 04:52:45

问题


I'm aware that this may have been answered before but please check that other answers are relevant to this instance!

I'm writing an array to a file as a string so that it can be stored when my script isn't running and be accessed again easily when run. When I then read this string out of the file again it is automatically read as a string.

I can fix this with a for loop that iterates through the saved string and appends each entry to an empty array, but that seems like overkill - is it? Is there a better way to read a string and convert it to an array?

So... something like this runs the first time in order to generate an array and write it to a file as a string:

the_file = open('.the_file.txt', 'w')
the_array = [10, 20, 30, 40, 50]
the_file.write(str(the_array))
the_file.close()

The next time the code is run a different section of code gets run that is something like this:

the_file = open('.the_file.txt', 'r')
the_array = the_file.read()
the_file.close()

If I print the the_array variable and its type at this point I get:

[10, 20, 30, 40, 50]
<type 'str'>

So I follow the advice given in this similar question here and do:

the_array = np.asarray(the_array)

...and then print the the_array variable and its type at this point to check that this has worked, to get:

[10, 20, 30, 40, 50]
<type 'numpy.ndarray'>

But now when I run the rest of my code I get the error:

TypeError: iteration over a 0-d array

Traced back to this part of my code:

the_array = sorted(the_array, reverse=True)

Can anyone help me out here; why does python think that my array is 0-d?


回答1:


the_array = np.asarray(the_array) is creating an array with one element in it: your string "[10, 20, 30, 40, 50]". Rather than read your file in, if you import json and replace the_array = the_file.read() with the_array = json.load(the_file), you'll get a list instead and can easily convert it to a numpy array.



来源:https://stackoverflow.com/questions/36579105/why-does-python-think-my-array-is-0-d-typeerror-iteration-over-a-0-d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!