简体   繁体   English

从文件中读取二维数组

[英]Reading 2D array from file

Im working on a simulation project in Python and encountered a problem.我在 Python 的一个模拟项目上工作,遇到了一个问题。 I need to save a 2D array to a file, so I can use data from it later.我需要将二维数组保存到文件中,以便稍后使用其中的数据。 The initial list looks like this:初始列表如下所示:

int_array3 = [[14,5], [9,3], [25,5]]
#writing to file:
with open('data.txt', 'w') as f:
for num in int_array3:
    f.write("%s\n" % num)

The data in file looks like this:文件中的数据如下所示:

[14  5]
[9 3]
[25  6]

I have tired this piece of code to read it, but it is not an integer list.我已经厌倦了这段代码来阅读它,但它不是 integer 列表。

with open('data.txt', 'r') as f:
result = f.readlines()
result = [x.strip() for x in result]

The result list looks like this:结果列表如下所示:

['[14  5]', '[9 3]', '[25  6]']

Can someone recommend me how to make it work?有人可以推荐我如何让它工作吗? I want the result list to be shaped the same way my initial list was.我希望结果列表的形状与我的初始列表相同。 I am using numpy.我正在使用 numpy。

How about writing only numbers without [] to file?仅将不带[]的数字写入文件怎么样? You can achieve that with nested for loop during writing to file.您可以在写入文件期间使用嵌套for循环来实现这一点。 Just remember to separate numbers (with space for example).只需记住分隔数字(例如用空格)。 Then, you could read your file line by line, use split() , and then you'll have an array of numbers, but for now it's an array of strings.然后,您可以逐行读取文件,使用split() ,然后您将拥有一个数字数组,但现在它是一个字符串数组。 To make numbers out of it, you'd need to cast string numbers to int.要从中生成数字,您需要将字符串数字转换为 int。 I think the easiest way would be using list comprehension to build new list of numbers.我认为最简单的方法是使用列表推导来构建新的数字列表。

To illustrate the above, your writing code would be like this:为了说明上述情况,您的编写代码将如下所示:

int_array3 = [[14,5], [9,3], [25,5]]
#writing to file:
with open('data.txt', 'w') as f:
for vec in int_array3:
    for number in vec:
        f.write("%d " % number)
    f.write("\n")

And you could read your wile with:你可以阅读你的诡计:

with open('data.txt', 'r') as f:
for line in f:
    vector = [int(x) for x in line.split()]
    #Do something with vector variable

You can try using eval() to convert the string to an array like so:您可以尝试使用eval()将字符串转换为数组,如下所示:

A = ['[14  5]', '[9 3]', '[25  6]']
arr = []

for i in range(len(A)):
    l = eval(A[i].split()[0] + ',' + A[i].split()[1])
    arr.append(l)

print(A)
# [[14, 5], [9, 3], [25, 6]]

Feel free to ask for clarifications随时要求澄清

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM