简体   繁体   English

itertools.repeat(object[, times]) 如何在运行时有选择地设置时间选项?

[英]itertools.repeat(object[, times]) How do I optionally set the times option at runtime?

I have a loop:我有一个循环:

for x in itertools.repeat(1)

Depending on the cmd line parameters I need this to be infinite or x number of times.根据 cmd 行参数,我需要无限次或x次。

So this所以这

for x in itertools.repeat(1)

or this或这个

for x in itertools.repeat(1, x)

How can I do this?我怎样才能做到这一点?

itertools.repeat returns an iterable, so you can do this: itertools.repeat返回一个可迭代对象,因此您可以执行以下操作:

import sys
import itertools

if len(sys.argv) > 1:
    repeater = itertools.repeat(1, int(sys.argv[1]))
else:
    repeater = itertools.repeat(1)

for x in repeater:
    print x

sys.argv is the cli inputs; sys.argv是 cli 输入; argv[0] will always be the script name, so I'm assuming argv[1] will be your input. argv[0]将始终是脚本名称,所以我假设argv[1]将是您的输入。

It's Python, so you can do this: if myCondition is the thing you want to test (eg a == 2 ), then:它是 Python,所以你可以这样做:如果myCondition是你想要测试的东西(例如a == 2 ),那么:

myIterator = itertools.repeat(1) if myCondition else itertools.repeat(1, x)

for x in myIterator:
    do-something

You can use islice instead of the second argument to limit the number of items returned.您可以使用islice代替第二个参数来限制返回的项目数。

import argparse
import itertools

p = argparse.ArgumentParser()
p.add_argument("--count", type=int, default=None)
args = p.parse_args()

ones = itertools.repeat(1)
for x in itertools.islice(ones, args.count):
    ...

If the stop argument to islice is None , then there is no upper limit on the number of items in the slice.如果islicestop参数是None ,则切片中的项目数没有上限。


I'm surprised that repeat itself does not accept None to explicitly trigger the default behavior.我很惊讶repeat本身不接受None来明确触发默认行为。 I submitted a bug report ;我提交了一个错误报告 we'll see if the maintainers consider it a bug as well.我们会看看维护者是否也认为它是一个错误。

Here's a quick one-liner solution that's nice compact which I used, I wanted to repeat an infinite number of times or only once, you can use this:这是我使用的一个非常紧凑的快速单线解决方案,我想重复无数次或只重复一次,您可以使用它:

itertools.repeat(my_object, *([] if my_condition else [1]))

The argument expansion won't happen for the [] case and thus you get the effect of None you would expect based on the documentation and (in my opinion) a reasonable reading of the functions purpose. []情况下不会发生参数扩展,因此根据文档和(在我看来)对函数目的的合理阅读,您会得到您期望的None效果。

Otherwise [1] will expand to times=1 , you could replace 1 with whatever value you wanted.否则[1]将扩展为times=1 ,您可以用您想要的任何值替换 1 。

times=None would have been cleaner, but c'est las vie, the maintainers didn't want it ( https://bugs.python.org/issue34169 ). times=None会更干净,但是 c'est las vie,维护者不想要它( https://bugs.python.org/issue3416​​9 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM