python为什么认为我的数组是0-d? (TypeError:在0维数组上的迭代) [英] Why does python think my array is 0-d? (TypeError: iteration over a 0-d array)

查看:492
本文介绍了python为什么认为我的数组是0-d? (TypeError:在0维数组上的迭代)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道之前可能已经回答过此问题,但请检查其他答案是否与此实例相关!

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.

我可以使用for循环来解决此问题,该循环遍历保存的字符串并将每个条目附加到一个空数组,但这似乎有点过头了-是吗?有没有更好的方法来读取字符串并将其转换为数组?

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()

如果此时打印the_array变量及其类型,我将得到:

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)

...,然后在此时打印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)

有人可以在这里帮助我吗? python为什么认为我的数组是0-d?

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

推荐答案

the_array = np.asarray(the_array)正在创建一个包含一个元素的数组:您的字符串"[10, 20, 30, 40, 50]".如果您import json并将the_array = the_file.read()替换为the_array = json.load(the_file),则无需读入文件,而是获得一个列表,并且可以轻松地将其转换为numpy数组.

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.

这篇关于python为什么认为我的数组是0-d? (TypeError:在0维数组上的迭代)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆