Re: [問題] for statement

看板Python作者 (朱子)時間12年前 (2013/05/25 13:16), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《sean72 (.)》之銘言: : 1. : 我在stack overflow看到別人舉了這個例子 : 能意會,卻無法行行了解 : def print_everything(*args): : for count, thing in enumerate(args): : print ('{0}. {1}'.format(count, thing)) : print_everything('apple', 'banana', 'cabbage') : 那並不是一個保留關鍵字 : 為什麼他的count為什麼可以這樣用? : thing in enumerate 也不懂為何可以這樣用 : 我想自己上網找文件 : 卻不知道該搜索什麼關鍵字 因為你斷句錯了 不是 for count, thin in enumerate(args): 而是 for count,thin in enumerate(args): enumerate() 會回傳一個 iterator 這個iterator的每個 item是一個 tuple 例如 >>> fruits = enumerate(['apple', 'banana', 'cabbage']) >>> fruits.next() (0, 'apple') >>> fruits.next() (1, 'banana') >>> fruits.next() (2, 'cabbage') >>> fruits.next() Traceback (most recent call last): File "<stdin>", line 5, in <module> StopIteration for count,thin in enumerate(['apple','banana','cabbage']): print ('{0}. {1}'.format(count, thing)) 就等於 it = enumerate(['apple','banana','cabbage']) while True: try: count,thin = it.next() # 第一執行時 count,thin = (1, 'apple') # 也就是 count = 1 ; thin = 'apple' print ('{0}. {1}'.format(count, thing)) # 印出 "1. apple" except StopIteration: break # 若 iter 沒有下一項時跳出迴圈 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.57.113.14 ※ 編輯: mantour 來自: 61.57.113.14 (05/25 13:24) ※ 編輯: mantour 來自: 61.57.113.14 (05/25 13:26)
文章代碼(AID): #1He4aftK (Python)
討論串 (同標題文章)
本文引述了以下文章的的內容:
3
5
完整討論串 (本文為第 2 之 2 篇):
3
5
文章代碼(AID): #1He4aftK (Python)