[英]Why does python recognise my object even when I haven't defined it?
美好的一天!
我正在閱讀並嘗試學習Python的書中的樣本可以幫助我嗎?
對於下面顯示的代碼。 我從來沒有定義過“ each_score”,那么為什么這個“ each_score”會被Python識別並運行正常呢?
scores={}
result_f=open("py score.txt")
for line in result_f:
(name,score)=line.split()
scores[score]=name
result_f.close()
print("The top scores were:")
for each_score in scores.keys():
print('surfer '+scores[each_score]+' scored '+each_score)
順便說一下,文本文件的內容很簡單,如下所示:
Johnny 8.65
Juan 9.12
Joseph 8.45
Stacey 7.81
Aideen 8.05
Zack 7.21
Aaron 8.31
不,您已經在for
循環中定義了它。
在您的示例中,變量應從鍵中獲取第一個值,在第二次迭代中,應獲取第二個值,依此類推。
您正在循環中定義它。 每次迭代each_score
都會獲取score.keys()
的當前值。
注意-不是答案,而是一個很大的注釋,不會在注釋字段中格式化...只是一些學習技巧(由於電池快要耗盡,我必須寫得很快...)
您應該在需要自動資源關閉的地方使用with
(請參閱高級手冊)...理解可能很有用(請參見下面的dict
位)...變量的“正確”命名也很好-在這種情況下, surfer_scores
...拆開諸如for surfer, score
元組for surfer, score
也增加了可讀性,並且使用字符串格式而不是concat'ing也很有用。
因此,在您完成了必要的學習工作之后,上面的代碼可能會變成類似以下內容:
with open('py score.txt') as fin:
surfer_scores = dict(line.split() for line in fin)
for surfer, score in surfer_scores.iteritems():
print('Surfer {} scored {} points'.format(surfer, score))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.