Python 迭代一定次数而不将迭代次数存储在任何地方
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3685974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate a certain number of times without storing the iteration number anywhere
提问by BorrajaX
I was wondering if it is possible to perform a certain number of operations without storing the loop iteration number anywhere.
我想知道是否可以在不将循环迭代次数存储在任何地方的情况下执行一定数量的操作。
For instance, let's say I want to print two "hello"messages to the console. Right now I know I can do:
例如,假设我想向"hello"控制台打印两条消息。现在我知道我可以做到:
for i in range(2):
print "hello"
but then the ivariable is going to take the values 0and 1(which I don't really need). Is there a way to achieve the same thing without storing those unwanted values anywhere?
但随后i变量将采用值0和1(我并不真正需要)。有没有办法在不将这些不需要的值存储在任何地方的情况下实现相同的目标?
采纳答案by BorrajaX
The idiom (shared by quite a few other languages) for an unused variable is a single underscore _. Code analysers typically won't complain about _being unused, and programmers will instantly know it's a shortcut for i_dont_care_wtf_you_put_here. There is no way to iterate without having an item variable - as the Zen of Python puts it, "special cases aren't special enough to break the rules".
未使用变量的习惯用法(由许多其他语言共享)是单个下划线_。代码分析器通常不会抱怨_未使用,程序员会立即知道这是i_dont_care_wtf_you_put_here. 没有 item 变量就没有办法进行迭代——正如 Python 的 Zen 所说,“特殊情况不足以打破规则”。
回答by nmichaels
for word in ['hello'] * 2:
print word
It's not idiomatic Python, but neither is what you're trying to do.
它不是惯用的 Python,但也不是您想要做的。
回答by recursive
exec 'print "hello";' * 2
should work, but I'm kind of ashamed that I thought of it.
应该工作,但我有点惭愧,我想到了它。
Update:Just thought of another one:
更新:刚刚想到另一个:
for _ in " "*10: print "hello"
回答by Walter
Although I agree completely with delnan's answer, it's not impossible:
虽然我完全同意 delnan 的回答,但这并非不可能:
loop = range(NUM_ITERATIONS+1)
while loop.pop():
do_stuff()
Note, however, that this will not work for an arbitrary list: If the first value in the list (the last one popped) does not evaluate to False, you will get another iteration and an exception on the next pass: IndexError: pop from empty list. Also, your list (loop) will be empty after the loop.
但是,请注意,这不适用于任意列表:如果列表中的第一个值(弹出的最后一个值)不计算为False,您将在下一次传递中获得另一次迭代和异常:IndexError: pop from empty list。此外,loop循环后您的列表 ( ) 将为空。
Just for curiosity's sake. ;)
只是为了好奇。;)
回答by user3399731
Sorry, but in order to iterate over anything in any language, Python and English included, an index must be stored. Be it in a variable or not. Finding a way to obscure the fact that python is internally tracking the for loop won't change the fact that it is. I'd recommend just leaving it as is.
抱歉,为了迭代任何语言(包括 Python 和英语)中的任何内容,必须存储索引。无论是否在变量中。找到一种方法来掩盖 python 在内部跟踪 for 循环的事实不会改变它的事实。我建议保持原样。
回答by ThorSummoner
Well I think the forloop you've provided in the question is about as good as it gets, but I want to point out that unused variables that have to be assigned can be assigned to the variable named _, a convention for "discarding" the value assigned. Though the _reference will hold the value you gave it, code linters and other developers will understand you aren't using that reference. So here's an example:
好吧,我认为您在问题中提供的 forloop 与其得到的一样好,但我想指出,必须分配的未使用变量可以分配给名为 的变量_,这是“丢弃”值的约定分配。尽管_引用将保存您给它的值,但代码检查器和其他开发人员会理解您没有使用该引用。所以这是一个例子:
for _ in range(2):
print('Hello')
回答by ShadowRanger
Others have addressed the inability to completely avoid an iteration variable in a forloop, but there are options to reduce the work a tiny amount. rangehas to generate a whole bunch of numbers after all, which involves a tiny amount of work; if you want to avoid even that, you can use itertools.repeatto just get the same (ignored) value back over and over, which involves no creation/retrieval of different objects:
其他人已经解决了无法完全避免循环中的迭代变量的问题for,但有一些选项可以减少工作量。range毕竟要生成一大堆数字,工作量很小;如果您甚至想避免这种情况,您可以使用itertools.repeat来一遍又一遍地获取相同(忽略)的值,这不涉及创建/检索不同对象:
from itertools import repeat
for _ in repeat(None, 200): # Runs the loop 200 times
...
This will run faster in microbenchmarks than for _ in range(200):, but if the loop body does meaningful work, it's a drop in the bucket. And unlike multiplying some anonymous sequence for your loop iterable, repeathas only a trivial setup cost, with no memory overhead dependent on length.
这将在微基准测试中运行得比 快for _ in range(200):,但如果循环体做了有意义的工作,那就是杯水车薪。与为循环迭代乘以一些匿名序列不同,repeat它只有微不足道的设置成本,没有依赖于长度的内存开销。
回答by Rasmus Pedersen
This will print 'hello' 3 times without storing i...
这将打印 'hello' 3 次而不存储i...
[print('hello') for i in range(3)]
回答by sairam546
You can simply do
你可以简单地做
print 2*'hello'

