請容易,我是學生!將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
你應該發佈預期的輸出...我們不知道你想寫所有的嘗試和/或只是最後的消息... –