请放轻松,我是一名学生!
我无法将以下代码的结果导出到 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))
最佳答案
import pandas as pd
import numpy as np
#get the flipcount
flipcount = int(input("How many times should I flip a coin?\n###:"))
samples = np.random.randint(0, 2, size = flipcount)
#create a pandas dataframe
data = pd.DataFrame(["heads" if i == 1 else "Tails" for i in samples])
#create a csv file
data.to_csv("data.csv", index=False, header=False)
关于python - 将 Python 结果导出到 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38252657/