[英]Python: Float Object is not Iterable
我寫了下面的代碼來完成任務:
fname = raw_input("Enter file name: ")
fh = open(fname)
total = 0
count = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
pos = line.find(':')
num = float(line[pos+1:])
for number in num:
total = total +num
count += 1
print 'Average spam confidence:', total/count
系統不斷地出現錯誤信息閱讀
浮動對象不可迭代
我知道我從for number in num:
犯了一個錯誤,正確答案是:
fname = raw_input("Enter file name: ")
fh = open(fname)
total = 0
count = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
pos = line.find(':')
num = float(line[pos+1:])
total = total +num
count += 1
print 'Average spam confidence:', total/count
但我的問題是:在正確答案中,浮動對象是否也是可迭代的? 謝謝您的幫助!!
正如 Python詞匯表所指出的,如果一個對象“能夠一次返回一個成員”,那么它就是一個可迭代對象。 num
是一個浮點數,它只是一個數字,它不能像列表、集合或字典一樣一次返回一個元素。 因此, for number in num:
寫入for number in num:
是沒有意義的for number in num:
- 為了使其工作, num
應該是一個可迭代的,以便它可以一次返回一個成員作為number
。 相反,您應該通過調用total = total + num
(或者甚至更好, total += num
)直接將num
添加到total
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.