我有以下python代码。它应该以表格格式将输出打印到csv文件中,例如
A B C D E F G H I J
2 4 5 7 9 7 6 5 4 2
.
.
.
但输出是每行打印一个值
A
B
C
.
.
.
2
3
4
.
.
这是代码
import random
import csv
with open('table.csv', 'w') as file:
csv_write = csv.writer(file,delimiter='\t')
for i in range(ord('A'), ord('J')+1):
row = [chr(i)]
csv_write.writerow(row)
for j in range(1,11):
for k in range(1,1001):
row2 = [random.randint(1,10001)]
csv_write.writerow(row2)
答案 0 :(得分:1)
import random
import csv
with open('table.csv', 'w', newline='') as file:
csv_write = csv.writer(file,delimiter='\t')
header = [ chr(i) for i in range(ord('A'), ord('J')+1)]
csv_write.writerow(header)
for k in range(1,1001):
row = random.sample(range(1,10001), 10)
csv_write.writerow(row)
答案 1 :(得分:0)
列出外部循环。
import random
import csv
with open('table.csv', 'w') as file:
csv_write = csv.writer(file, delimiter=',')
col = []
row2 = []
for i in range(ord('A'), ord('J')+1):
col.append(chr(i))
csv_write.writerow(col)
for j in range(1):
for k in range(1,11):
row2.append(random.randint(1,10))
csv_write.writerow(row2)
`