【发布时间】:2020-08-09 21:50:46
【问题描述】:
好的,所以我正在做一个模拟掷骰子的程序,然后将它们保存到一个文件中。 我认为,在我看来,最简单的选择就是保存循环的每一次迭代并将打印逐行保存到文件中。但不幸的是,我无法弄清楚。
import random
output=[]
order=0
inpu_t=int(input("Enter the number of simulated throws: "))
f = open('file.txt','w')
figures = (0,)*6
for i in range(inpu_t):
order = order+1
throw = random.randint(1, 6)
figure = figures[throw -1]+1
print(order,'.throw and {}-times fell the number {}.'.format(figure, throw ))
output.append(order)
output.append(figure)
output.append(throw )
figures = figures[:throw -1]+(figure,)+figures[throw :]
print("\n")
with open('file.txt', 'w') as f:
for item in output:
f.write("%s" % item)
for i in range(6):
print('The number {} fell {}-times.'.format(i+1, figures[i]))
其次,我认为我可以将所有变量保存到列表中,然后以某种方式通过某些函数将其保存到文件中。
output.append(order)
output.append(figure)
output.append(throw )
我将所有数据添加到列表中。
with open('file.txt', 'w') as f:
for item in output:
f.write("%s" % item)
我在此处将其添加到文件中。 我在文件中的输出是这样的:“115216314412511” 我不知道我应该怎么做才能让所有 3 个数字像代码一样在一行中。
print(order,'.throw and {}-times fell the number {}.'.format(figure, throw ))
【问题讨论】: