看板 Python 關於我們 聯絡資訊
※ 引述《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)