请容易,我是学生!将Python结果导出为CSV
我无法将以下代码的结果导出到CSV中。对于每一个循环(硬币翻转),我需要将结果导出为名为RESULTS.CSV的CSV作为新的ROW。
我尝试了四种不同的方法发布在StackOverflow上,但迄今为止还没有成功。我很难理解语法/逻辑。我讨厌这个问题,总是试图避免它,但是有谁会介意给我一个简单的解决方案,以便我可以剖析逻辑? (而不是引用到文章中,我已经尝试去理解他们,但我有麻烦)
版本:Python的3.5
import random
flipcount=int(input("How many times should I flip a coin?\n###:"))
samples = [ random.randint(1, 2) for i in range(flipcount) ]
heads = samples.count(1)
tails = samples.count(2)
for s in samples:
msg = 'Heads' if s==1 else 'Tails'
print(msg)
print ("Heads count=%d, Tails count=%d" % (heads, tails))
这是一次失败的尝试。我相信我已经饱和我对这个话题的研究并且让我很困惑......
import random
import csv
flipcount=int(input("How many times should I flip a coin?\n###:"))
samples = [ random.randint(1, 2) for i in range(flipcount) ]
heads = samples.count(1)
tails = samples.count(2)
writer = csv.writer(w)
for s in samples:
msg = 'Heads' if s==1 else 'Tails'
print(msg)
with open('some.csv', 'w', newline='') as f:
writer.writerows(msg)
print ("Heads count=%d, Tails count=%d" % (heads, tails))
我认为这将是有益的张贴失败的尝试。另外,看看旧的stackoverflow问题,因为这个问题并不新鲜。 – ishaan
你应该发布预期的输出...我们不知道你想写所有的尝试和/或只是最后的消息... –