[問題] for statement

看板Python作者 (.)時間12年前 (2013/05/24 04:52), 編輯推噓3(302)
留言5則, 3人參與, 最新討論串1/2 (看更多)
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 也不懂為何可以這樣用 我想自己上網找文件 卻不知道該搜索什麼關鍵字 === 2. 上python.org查了 for 他給了另外一個簡單的例子 words = ['cat', 'window', 'defenestrate'] for w in words: print w, len(w) 為什麼 for w in words 會自然而然的代表出 list裡面的cat windwo defenestrate 而不需要表示成 word[0] word[1] word[2] 為什麼不是先用len取得list長度 然後 print w for len(words) 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 204.96.168.3 ※ 編輯: sean72 來自: 204.96.168.3 (05/24 05:01)

05/24 10:42, , 1F
試試看 google 'python generator'
05/24 10:42, 1F

05/24 12:09, , 2F
你用for迴圈的時候就會自動去抓物件裡面的元素啊 字串抓字
05/24 12:09, 2F

05/24 12:09, , 3F
母 列表抓元素 字典應該是抓key出來吧
05/24 12:09, 3F

05/24 22:08, , 4F
count 的用法是 enumerate 的傳回值做 pattern matching
05/24 22:08, 4F

05/24 22:10, , 5F
第二個問題,建議可以瞭解一下 iterator 的思考方式
05/24 22:10, 5F
文章代碼(AID): #1Hde68wN (Python)
討論串 (同標題文章)
文章代碼(AID): #1Hde68wN (Python)