作者mantour (朱子)
看板Python
标题Re: [问题] for statement
时间Sat May 25 13:16:22 2013
※ 引述《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)