为什么python认为我的数组是0-d? (TypeError:在0-d数组上迭代)

时间:2016-04-12 16:30:54

标签: python arrays numpy iteration sorted

我知道这可能之前已经得到了解答,但请检查其他答案是否与此实例相关!

我将一个数组作为字符串写入文件,以便在我的脚本运行时可以存储它,并在运行时再次轻松访问。当我再次从文件中读取该字符串时,它会自动读取为字符串。

我可以使用for循环修复此问题,循环遍历已保存的字符串并将每个条目附加到空数组,但这看起来有点矫枉过正 - 是吗?有没有更好的方法来读取字符串并将其转换为数组?

所以...这样的东西第一次运行,以生成一个数组并将其作为字符串写入文件:

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

下次运行代码时,会运行不同的代码段,如下所示:

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

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

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

所以我遵循this similar question here中给出的建议并执行:

the_array = np.asarray(the_array)

...然后在此时打印the_array变量及其类型以检查这是否有效,以获得:

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

但是现在当我运行剩下的代码时,我得到了错误:

TypeError: iteration over a 0-d array

追溯到我的代码的这一部分:

the_array = sorted(the_array, reverse=True)

任何人都可以帮助我;为什么python认为我的数组是0-d?

1 个答案:

答案 0 :(得分:3)

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数组。