Python 惯用语:“times”环形

发布于 2024-08-28 20:41:34 字数 246 浏览 2 评论 0原文

假设我有一个函数 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

绮烟 2024-09-04 20:41:34

您已经展示了惯用的方式:

for _ in range(n): # or xrange if you are on 2.X
    foo()

不确定这有什么“hackish”。如果您有更具体的用例,请提供更多详细信息,可能会有更适合您正在做的事情。

You've already shown the idiomatic way:

for _ in range(n): # or xrange if you are on 2.X
    foo()

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.

梦醒灬来后我 2024-09-04 20:41:34

如果您想要 times 方法,并且需要在自己的函数上使用它,请尝试以下操作:

def times(self, n, *args, **kwargs):
    for _ in range(n):
        self.__call__(*args, **kwargs)

import new
def repeatable(func):
    func.times = new.instancemethod(times, func, func.__class__)
    return func

现在向您需要 的任何方法添加一个 @repeatable 装饰器times 方法:

@repeatable
def foo(bar):
    print bar

foo.times(4, "baz") #outputs 4 lines of "baz"

If you want the times method, and you need to use it on your own functions, try this:

def times(self, n, *args, **kwargs):
    for _ in range(n):
        self.__call__(*args, **kwargs)

import new
def repeatable(func):
    func.times = new.instancemethod(times, func, func.__class__)
    return func

now add a @repeatable decorator to any method you need a times method on:

@repeatable
def foo(bar):
    print bar

foo.times(4, "baz") #outputs 4 lines of "baz"
酒儿 2024-09-04 20:41:34

最快、最干净的是 itertools.repeat

import itertools

for _ in itertools.repeat(None, n):
    foo()

Fastest, cleanest is itertools.repeat:

import itertools

for _ in itertools.repeat(None, n):
    foo()
書生途 2024-09-04 20:41:34

这个问题预先假设调用 foo() n 次是先验必要的事情。 n从哪里来?它是可迭代对象的长度吗?然后迭代可迭代对象。当我开始学习 Python 时,我发现我几乎没有使用任意值; n 背后有一些更显着的含义,当它变成整数时就丢失了。

今天早些时候,我偶然发现了 Nicklaus Wirth 为 IEEE Computer 发表的一篇颇具争议性的论文,题为 好主意 - 透过镜子(存档版本供未来读者使用)。在第 4 节中,他对每个人(包括他自己)都认为理所当然但存在表达缺陷的编程结构提出了不同的倾向:

“Algol for 的一般性
声明应该是一个警告
向所有未来的设计师发出信号
始终保持首要目的
牢记于心,并厌倦
夸大普遍性和复杂性,
这很容易成为
适得其反。”

algol for 相当于 C/Java for,它只是做了太多的事情。那篇论文是一本有用的读物​​,只是因为它使人不我们如此容易地认为这是理所当然的,所以也许更好的问题是“为什么需要一个执行任意次数的循环?”

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 generality of Algol’s for
statement should have been a warning
signal to all future designers to
always keep the primary purpose of a
construct in mind, and to be weary of
exaggerated generality and complexity,
which may easily become
counter-productive."

The algol for is equivalent to the C/Java for, 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?"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文