不是“多”或“少”可以理解,而是你如何描述它:
-
for x in something
:迭代来自iterable的值
something
作为变量
x
. 所以你需要解释的是
range(...)
“。
-
range(start, end,...)
返回从开始(包含)到停止(排除)生成整数序列的对象。给他们看看
help(range)
你问的是“如何使for循环更像c?”
有一些方法可以做到这一点:
def nrange(start, num_elements, step=1):
"""Similar to `range`, but second argument is number of elements."""
return range(start, start + step*num_elements, step)
def inclusive_range(start_or_stop, stop=None, step=1):
if stop is None:
start = 0
stop = start_or_stop+1
else:
start = start_or_stop
stop = stop + step
return range(start, stop, step)
_default_update_func = lambda item: item+1
def c_like_iterator(start, test_func, update_func=_default_update_func):
cur_value = start
while test_func(cur_value):
yield cur_value
cur_value = update_func(cur_value)
for i in nrange(1, 10):
print(i)
for i in inclusive_range(1, 10):
print(i)
for i in inclusive_range(10): # this will give 11 elements because both 0 and 10 values are included
print(i)
for i in c_like_iterator(1, lambda x: x<=10, lambda x: x+1):
print(i)
for i in c_like_iterator(1, lambda x: x<11, lambda x: x+1):
print(i)
for i in inclusive_range(1, -10, -1):
print(i)