作者sean72 (.)
看板Python
標題[問題] for statement
時間Fri May 24 04:52:21 2013
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)
推 IrisXIII:試試看 google 'python generator' 05/24 10:42
推 Yukirin:你用for迴圈的時候就會自動去抓物件裡面的元素啊 字串抓字 05/24 12:09
→ Yukirin:母 列表抓元素 字典應該是抓key出來吧 05/24 12:09
推 letoh:count 的用法是 enumerate 的傳回值做 pattern matching 05/24 22:08
→ letoh:第二個問題,建議可以瞭解一下 iterator 的思考方式 05/24 22:10