Which is more pythonic?
哪个更pythonic?
While loop:
循环:
count = 0
while count < 50:
print "Some thing"
count = count + 1
For loop:
对于循环:
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'的范围 - 尽管最终是最优雅的
5 个解决方案
#1
76
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 xrange
as there is no need to generate the whole list beforehand.
如果你不需要我如果您使用Python <3并且想要多次重复循环,请使用xrange,因为不需要事先生成整个列表。
#2
1
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 map
approach. Something like this:
如果你关心你在循环中调用的任何函数的结果,我会选择列表理解或映射方法。像这样的东西:
def f(n):
return n * n
results = [f(i) for i in range(50)]
# or using map:
results = map(f, range(50))
#3
1
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 i
variable, stem from the absence of a statement like Verilog's repeat
statement. The main reason to stick to the for range solution is that other ways are more complex. For instance:
for循环肯定更加pythonic,因为它使用Python的更高级别内置功能来更清晰,更简洁地传达您正在做的事情。范围与xrange的开销,以及分配未使用的i变量,源于缺少像Verilog的重复语句这样的语句。坚持范围解决方案的主要原因是其他方式更复杂。例如:
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 Python and 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 reference and 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-style for循环的while扩展更熟悉。
#4
-4
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__()
#5
-6
There is not a really pythonic way of repeating something. However, it is a better way:
没有一种真正的pythonic方式来重复某些事情。但是,这是一个更好的方法:
map(lambda index:do_something(), xrange(10))
map(lambda index:do_something(),xrange(10))
if you need to pass the index then:
如果你需要传递索引,那么:
map(lambda index:do_something(index), xrange(10))
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.
考虑它将结果作为集合返回,因此如果您需要收集结果,它可以提供帮助。
#1
76
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 xrange
as there is no need to generate the whole list beforehand.
如果你不需要我如果您使用Python <3并且想要多次重复循环,请使用xrange,因为不需要事先生成整个列表。
#2
1
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 map
approach. Something like this:
如果你关心你在循环中调用的任何函数的结果,我会选择列表理解或映射方法。像这样的东西:
def f(n):
return n * n
results = [f(i) for i in range(50)]
# or using map:
results = map(f, range(50))
#3
1
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 i
variable, stem from the absence of a statement like Verilog's repeat
statement. The main reason to stick to the for range solution is that other ways are more complex. For instance:
for循环肯定更加pythonic,因为它使用Python的更高级别内置功能来更清晰,更简洁地传达您正在做的事情。范围与xrange的开销,以及分配未使用的i变量,源于缺少像Verilog的重复语句这样的语句。坚持范围解决方案的主要原因是其他方式更复杂。例如:
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 Python and 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 reference and 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-style for循环的while扩展更熟悉。
#4
-4
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__()
#5
-6
There is not a really pythonic way of repeating something. However, it is a better way:
没有一种真正的pythonic方式来重复某些事情。但是,这是一个更好的方法:
map(lambda index:do_something(), xrange(10))
map(lambda index:do_something(),xrange(10))
if you need to pass the index then:
如果你需要传递索引,那么:
map(lambda index:do_something(index), xrange(10))
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.
考虑它将结果作为集合返回,因此如果您需要收集结果,它可以提供帮助。