[英]writing files python i think i have issue with else:count
編寫一個名為“internet_histogram”的函數,它不帶參數也不返回值。 測試環境中將有一個名為“survey.csv”的文件,其中包含如上所述的調查結果(該文件有一個標題行,大部分由您的代碼處理)。 編寫一個名為“histogram.csv”的新文件,其中包含 2 列代表“internet_use,frequency”,並且沒有標題行,其中將包含 28 至 29 歲響應者的結果直方圖,包括端點年齡。 您的文件將正好有 6 行,internet_use 值為 1-5,對應於 intfreq 結果,6 行用於回答 2 為 eminuse 的響應者。 閱讀調查結果文件並跟蹤在此年齡范圍內回答了這 6 個選項中的每個選項的響應者數量,並將這些計數按照 internet_use 從 1 開始的順序寫入您的“histogram.csv”文件。示例 histogram.csv:1,5 2 ,7 3,0 4,1 5,2 6,4
我的代碼:
import csv
def internet_histogram():
count_6 = 0
count_5 = 0
count_4 = 0
count_3 = 0
count_2 = 0
count_1 = 0
with open("survey.csv",'r') as f:
reader = csv.reader(f)
with open("histogram.csv", 'w') as g:
writer = csv.writer(g)
next(reader)
for line in reader:
if int(line[3]) >= 28 and int(line[3]) <= 29:
if line[2] != '':
if int(line[2]) == 1:
count_1 += 1
if int(line[2]) == 2:
count_2 += 1
if int(line[2]) == 3:
count_3 += 1
if int(line[2]) == 4:
count_4 += 1
if int(line[2]) == 5:
count_5 += 1
else:
count_6 = count_6 + 1
arr = [[1, count_1], [2, count_2], [3, count_3], [4, count_4], [5, count_5], [6, count_6]]
for i in arr:
writer.writerow(i)
輸出:寫道:“1,26 2,29 3,2 4,3 5,1 6,1”預期:“1,26 2,29 3,2 4,3 5,1 6,2”
我認為這是 else 語句的一個問題,但我不太確定,任何幫助將不勝感激。
按照現在的編寫方式,第6
列的計數始終為1
。
您應該縮進else
以便將此案例與其他案例一起計算,但使用else
只會引用最后一個if
,因此它將計算int(line[2]) != 5
所有案例,這可能不是不是你想要做的。
為了最好的python zen顯式,我將使用以下而不是else
:
if int(line[2]) not in [1, 2, 3, 4, 5]:
count_6 += 1
那對你有用嗎?
祝你好運!
我自己還不太精通 Python,但我通過在此處移動一些縮進以及其他一些小的更改來修復您的程序:
import csv
def internet_histogram():
count_6 = 0
count_5 = 0
count_4 = 0
count_3 = 0
count_2 = 0
count_1 = 0
with open("survey.csv",'r') as f:
reader = csv.reader(f)
with open("histogram.csv", 'w') as g:
writer = csv.writer(g)
next(reader)
for line in reader:
if int(line[3]) >= 28 and int(line[3]) <= 29:
if line[2] != '':
if int(line[2]) == 1:
count_1 += 1
elif int(line[2]) == 2:
count_2 += 1
elif int(line[2]) == 3:
count_3 += 1
elif int(line[2]) == 4:
count_4 += 1
elif int(line[2]) == 5:
count_5 += 1
else:
count_6 = count_6 + 1
arr = [[1, count_1], [2, count_2], [3, count_3], [4, count_4], [5, count_5], [6, count_6]]
for i in arr:
writer.writerow(i)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.