Python 惯用语:“times”环形
假设我有一个函数 foo
,我想调用它 n
次。在 Ruby 中,我会写:
n.times { foo }
在 Python 中,我可以写:
for _ in xrange(n): foo()
但这似乎是一种很奇怪的做事方式。
我的问题:Python 中有这样做的惯用方法吗?
Say I have a function foo
that I want to call n
times. In Ruby, I would write:
n.times { foo }
In Python, I could write:
for _ in xrange(n): foo()
But that seems like a hacky way of doing things.
My question: Is there an idiomatic way of doing this in Python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您已经展示了惯用的方式:
不确定这有什么“hackish”。如果您有更具体的用例,请提供更多详细信息,可能会有更适合您正在做的事情。
You've already shown the idiomatic way:
Not sure what is "hackish" about this. If you have a more specific use case in mind, please provide more details, and there might be something better suited to what you are doing.
如果您想要
times
方法,并且需要在自己的函数上使用它,请尝试以下操作:现在向您需要
的任何方法添加一个
方法:@repeatable
装饰器timesIf you want the
times
method, and you need to use it on your own functions, try this:now add a
@repeatable
decorator to any method you need atimes
method on:最快、最干净的是 itertools.repeat:
Fastest, cleanest is itertools.repeat:
这个问题预先假设调用 foo() n 次是先验必要的事情。 n从哪里来?它是可迭代对象的长度吗?然后迭代可迭代对象。当我开始学习 Python 时,我发现我几乎没有使用任意值; n 背后有一些更显着的含义,当它变成整数时就丢失了。
今天早些时候,我偶然发现了 Nicklaus Wirth 为 IEEE Computer 发表的一篇颇具争议性的论文,题为 好主意 - 透过镜子(存档版本供未来读者使用)。在第 4 节中,他对每个人(包括他自己)都认为理所当然但存在表达缺陷的编程结构提出了不同的倾向:
algol
for
相当于 C/Javafor
,它只是做了太多的事情。那篇论文是一本有用的读物,只是因为它使人不我们如此容易地认为这是理所当然的,所以也许更好的问题是“为什么需要一个执行任意次数的循环?”The question pre-supposes that calling foo() n times is an a priori necessary thing. Where did n come from? Is it the length of something iterable? Then iterate over the iterable. As I am picking up Python, I find that I'm using few to no arbitrary values; there is some more salient meaning behind your n that got lost when it became an integer.
Earlier today I happened upon Nicklaus Wirth's provocative paper for IEEE Computer entitled Good Ideas - Through the Looking Glass (archived version for future readers). In section 4 he brings a different slant on programming constructs that everyone (including himself) has taken for granted but that hold expressive flaws:
The algol
for
is equivalent to the C/Javafor
, it just does too much. That paper is a useful read if only because it makes one not take for granted so much that we so readily do. So perhaps a better question is "Why would you need a loop that executes an arbitrary number of times?"