是否可以在没有迭代器变量的情况下实现 Python for range 循环? [英] Is it possible to implement a Python for range loop without an iterator variable?
问题描述
是否可以在没有 i
的情况下进行以下操作?
for i in range(some_number):# 做点什么
如果你只想做 N 次的事情并且不需要迭代器.
在我的脑海里,没有.
我认为你能做的最好的事情是这样的:
def 循环(f,n):对于 xrange(n) 中的 i: f()循环(拉姆达:<在此处插入表达式>,5)
但我认为你可以忍受额外的 i
变量.
这里是使用 _
变量的选项,它实际上只是另一个变量.
for _ in range(n):做点什么()
请注意,_
被分配了在交互式 python 会话中返回的最后一个结果:
因此,我不会以这种方式使用它.我不知道瑞安提到的任何成语.它可能会弄乱你的口译员.
<预><代码>>>>对于 xrange(10) 中的 _:通过...>>>_9>>>1+23>>>_9并且根据Python语法,这是一个可接受的变量名:
identifier ::= (letter|"_") (letter | digit | "_")*
Is it possible to do following without the i
?
for i in range(some_number):
# do something
If you just want to do something N amount of times and don't need the iterator.
Off the top of my head, no.
I think the best you could do is something like this:
def loop(f,n):
for i in xrange(n): f()
loop(lambda: <insert expression here>, 5)
But I think you can just live with the extra i
variable.
Here is the option to use the _
variable, which in reality, is just another variable.
for _ in range(n):
do_something()
Note that _
is assigned the last result that returned in an interactive python session:
>>> 1+2
3
>>> _
3
For this reason, I would not use it in this manner. I am unaware of any idiom as mentioned by Ryan. It can mess up your interpreter.
>>> for _ in xrange(10): pass
...
>>> _
9
>>> 1+2
3
>>> _
9
And according to Python grammar, it is an acceptable variable name:
identifier ::= (letter|"_") (letter | digit | "_")*
这篇关于是否可以在没有迭代器变量的情况下实现 Python for range 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!