我有一个在Python中创建二维数组的程序但是如何将其保存为csv文件,它是
value_a = int(input("Type in a value for a: "))
value_b = int(input("Now a value for b: "))
value_c = int(input("And a value for c: "))
d = value_a + value_b + value_c
result = [[value_a, value_b, value_c, d]] # put the initial values into the array
number_of_loops = int(input("type in the number of loops the program must execute: "))
def loops(a, b, c, n):
global result
for i in range(n):
one_loop = [] # assign an empty array for the result of one loop
temp_a = a
a = ((a + 1) * 2) # This adds 1 to a and then multiplies by 2
one_loop.append(str(a))
b = b * 2
one_loop.append(b)
c = (temp_a + b)
one_loop.append(c)
d = a + b + c
one_loop.append(d)
result.append(one_loop)
print(result)
loops(value_a, value_b, value_c, number_of_loops)
print(result)
打印正常,但如何将数组保存为csv文件
答案 0 :(得分:0)
import csv
with open(filename, 'w') as f:
writer = csv.writer(f)
writer.writerows(result)
答案 1 :(得分:0)
如果您能够使用第三方库并且您将使用Python中的2d(或更多)数组,我建议您使用像numpy或pandas这样的库。 Numpy包含一种将数组写为名为savetxt
的csv文件的方法。祝你好运!
答案 2 :(得分:0)
Python带有CSV写入和阅读功能。有关更全面的文档,请参阅 The Python Standard Library » 13.1csv — CSV File Reading and Writing,但此处是从该页面获取并根据您的问题进行调整的快速示例:
import csv
with open('eggs.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row in results:
spamwriter.writerow(row)