可以不带i来做下面的事情吗?
for i in range(some_number):
# do something
如果你只是想做某件事N次而不需要迭代器。
可以不带i来做下面的事情吗?
for i in range(some_number):
# do something
如果你只是想做某件事N次而不需要迭代器。
当前回答
也许答案取决于你在使用迭代器时遇到了什么问题? 可能会使用
i = 100
while i:
print i
i-=1
or
def loop(N, doSomething):
if not N:
return
print doSomething(N)
loop(N-1, doSomething)
loop(100, lambda a:a)
但坦率地说,我认为使用这种方法没有任何意义
其他回答
如果do_something是一个简单的函数或者可以封装在一个简单的函数中,一个简单的map()可以do_something range(some_number)次:
# Py2 version - map is eager, so it can be used alone
map(do_something, xrange(some_number))
# Py3 version - map is lazy, so it must be consumed to do the work at all;
# wrapping in list() would be equivalent to Py2, but if you don't use the return
# value, it's wastefully creating a temporary, possibly huge, list of junk.
# collections.deque with maxlen 0 can efficiently run a generator to exhaustion without
# storing any of the results; the itertools consume recipe uses it for that purpose.
from collections import deque
deque(map(do_something, range(some_number)), 0)
如果你想将参数传递给do_something,你可能还会发现itertools repeatfunc recipe读起来很好:
通过相同的论点:
from collections import deque
from itertools import repeat, starmap
args = (..., my args here, ...)
# Same as Py3 map above, you must consume starmap (it's a lazy generator, even on Py2)
deque(starmap(do_something, repeat(args, some_number)), 0)
传递不同的参数:
argses = [(1, 2), (3, 4), ...]
deque(starmap(do_something, argses), 0)
每个人建议你使用_并不是说_经常被用作一个gettext函数的快捷方式,所以如果你想让你的软件在多种语言中可用,那么你最好避免将它用于其他目的。
import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print _('This is a translatable string.')
我们有一些乐趣与以下,有趣的分享:
class RepeatFunction:
def __init__(self,n=1): self.n = n
def __call__(self,Func):
for i in xrange(self.n):
Func()
return Func
#----usage
k = 0
@RepeatFunction(7) #decorator for repeating function
def Job():
global k
print k
k += 1
print '---------'
Job()
结果:
0
1
2
3
4
5
6
---------
7
也许答案取决于你在使用迭代器时遇到了什么问题? 可能会使用
i = 100
while i:
print i
i-=1
or
def loop(N, doSomething):
if not N:
return
print doSomething(N)
loop(N-1, doSomething)
loop(100, lambda a:a)
但坦率地说,我认为使用这种方法没有任何意义
现在您得到的不是一个不需要的计数器,而是一个不需要的列表。 最好的解决方案是使用一个以“_”开头的变量,这告诉语法检查器您知道您没有使用该变量。
x = range(5)
while x:
x.pop()
print "Work!"