繁体   English   中英

将二维数组写入python中的文本文件

[英]Write 2d array into a text file in python

我需要将大小为[5][3]的 2D 随机数组写入文本文件。 如何将它写在文本文件的一行中? 我从文件中得到的输出是矩阵形式,而不是一行。 我想把它写成一行的原因是我想为文本文件的第二行写另一个名为 max 的数组(我也不知道如何编码)。

import numpy as np
from numpy import random

process = 5
resources = 3
allocation = [[0 for i in range(resources)]for i in range(process)]

def writeFile(allocation, process, resources):
file = open("test.txt", 'w')
for i in range(process):
    for j in range(resources):
        allocation = random.randint(10, size=(5, 3))
file.write(str(allocation))
file.close()

return

if __name__ == '__main__':
writeFile(allocation, process, resources)

file = open("test.txt", 'r')
allocation = np.array(file.readlines())
print(*allocation)
file.close()
allocation = []
def writeFile(allocation, process, resources):
    file = open("test.txt", 'w')
    for i in range(process):
        temp = list(random.randint(10, size=(resources)))
        allocation.append(temp)
    file.write(str(allocation))
    file.close()
    return

您的代码为每次迭代生成一个随机的 5x3 矩阵。 为了在文件中写入一行,我将每一行附加为一个列表,并在最后将其转换为一个字符串。 上述代码的输出是:

[[0, 5, 9], [5, 4, 4], [7, 3, 9], [4, 6, 4], [9, 5, 8]]

暂无
暂无

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

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