运行进程 X 次的更多 Pythonic 方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4264634/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:59:17  来源:igfitidea点击:

More Pythonic Way to Run a Process X Times

pythonloops

提问by Lionel

Which is more pythonic?

哪个更pythonic?

While loop:

虽然循环:

count = 0
while count < 50:
    print "Some thing"
    count = count + 1

For loop:

For循环:

for i in range(50):
    print "Some thing"

Edit: not duplicate because this has answers to determine which is clearer, vs. how to run a range without 'i' -- even though that ended up being the most elegant

编辑:不重复,因为这有答案来确定哪个更清晰,与如何在没有 'i' 的情况下运行范围 - 即使最终是最优雅的

采纳答案by Felix Kling

Personally:

亲身:

for _ in range(50):
    print "Some thing"

if you don't need i. If you use Python < 3 and you want to repeat the loop a lot of times, use xrangeas there is no need to generate the whole list beforehand.

如果你不需要i. 如果您使用 Python < 3 并且想要多次重复循环,请使用,xrange因为无需事先生成整个列表。

回答by knutin

If you are after the side effects that happen within the loop, I'd personally go for the range()approach.

如果您追求循环内发生的副作用,我个人会采用这种range()方法。

If you care about the result of whatever functions you call within the loop, I'd go for a list comprehension or mapapproach. Something like this:

如果您关心在循环中调用的任何函数的结果,我会选择列表理解或map方法。像这样的东西:

def f(n):
    return n * n

results = [f(i) for i in range(50)]
# or using map:
results = map(f, range(50))

回答by Abi M.Sangarab

There is not a really pythonic way of repeating something. However, it is a better way:

没有一种真正的 Pythonic 方式来重复某些事情。但是,这是一个更好的方法:

map(lambda index:do_something(), xrange(10))

If you need to pass the index then:

如果您需要传递索引,则:

map(lambda index:do_something(index), xrange(10))

Consider that it returns the results as a collection. So, if you need to collect the results it can help.

考虑将结果作为集合返回。因此,如果您需要收集结果,它会有所帮助。

回答by Yann Vernier

The for loop is definitely more pythonic, as it uses Python's higher level built in functionality to convey what you're doing both more clearly and concisely. The overhead of range vs xrange, and assigning an unused ivariable, stem from the absence of a statement like Verilog's repeatstatement. The main reason to stick to the for range solution is that other ways are more complex. For instance:

for 循环肯定更加 Pythonic,因为它使用 Python 的更高级别的内置功能来更清晰、更简洁地传达您正在做的事情。range vs xrange 的开销,以及分配一个未使用的i变量,源于没有像 Verilog 的repeat语句那样的语句。坚持 for range 解决方案的主要原因是其他方式更复杂。例如:

from itertools import repeat

for unused in repeat(None, 10):
    del unused   # redundant and inefficient, the name is clear enough
    print "This is run 10 times"

Using repeat instead of range here is less clear because it's not as well known a function, and more complex because you need to import it. The main style guides if you need a reference are PEP 20 - The Zen of Pythonand PEP 8 - Style Guide for Python Code.

在这里使用 repeat 而不是 range 不太清楚,因为它不是众所周知的函数,而且更复杂,因为您需要导入它。如果您需要参考,主要的风格指南是PEP 20 - Python 之禅PEP 8 - Python 代码风格指南

We also note that the for range version is an explicit example used in both the language referenceand tutorial, although in that case the value is used. It does mean the form is bound to be more familiar than the while expansion of a C-style for loop.

我们还注意到 for range 版本是语言参考教程中使用的显式示例,尽管在这种情况下使用了值。这确实意味着这种形式肯定比 C 风格的 for 循环的 while 扩展更熟悉。

回答by DangerMouse

How about?

怎么样?

while BoolIter(N, default=True, falseIndex=N-1):
    print 'some thing'

or in a more ugly way:

或者以更丑陋的方式:

for _ in BoolIter(N):
    print 'doing somthing'

or if you want to catch the last time through:

或者如果您想通过以下方式捕捉最后一次:

for lastIteration in BoolIter(N, default=False, trueIndex=N-1):
    if not lastIteration:
        print 'still going'
    else:
        print 'last time'

where:

在哪里:

class BoolIter(object):

    def __init__(self, n, default=False, falseIndex=None, trueIndex=None, falseIndexes=[], trueIndexes=[], emitObject=False):
        self.n = n
        self.i = None
        self._default = default
        self._falseIndexes=set(falseIndexes)
        self._trueIndexes=set(trueIndexes)
        if falseIndex is not None:
            self._falseIndexes.add(falseIndex)
        if trueIndex is not None:
            self._trueIndexes.add(trueIndex)
        self._emitObject = emitObject


    def __iter__(self):
        return self

    def next(self):
        if self.i is None:
            self.i = 0
        else:
            self.i += 1
        if self.i == self.n:
            raise StopIteration
        if self._emitObject:
            return self
        else:
            return self.__nonzero__()

    def __nonzero__(self):
        i = self.i
        if i in self._trueIndexes:
            return True
        if i in self._falseIndexes:
            return False
        return self._default

    def __bool__(self):
        return self.__nonzero__()