gpt4 book ai didi

python - 通过列表值迭代有限但任意次数的最Pythonic方法

转载 作者:行者123 更新时间:2023-11-30 23:23:58 24 4
gpt4 key购买 nike

我正在尝试以遗传算法的方式优化某种结果。

我提供一个种子值作为函数的输入,该函数执行一些转换并返回“优值”。然后,我选择最佳种子值,并重复该过程,直到获得获胜者。

我遇到的挑战是,我想为每个步骤运行有限次数的试验(例如,最多 100 次),并且每次运行时种子值的数量变化很大。因此,仅使用 for 循环来查看种子值列表对我来说不起作用。

这是我想出的解决方案,用于处理不是无限迭代器的列表:

iterations = 100
rlist = list(d.keys())

for lt in (itertools.repeat(rlist)):
d = gatherseedvalues(directory)
seed = random.choice(lt)
goodness = goodnessgracious(seed)
goodnessdict[seed] = goodness
if len(goodnessdict) > iterations:
break

是否有更 Pythonic 的方法来做到这一点 - 无论是在绕过迭代器限制还是循环策略方面?

此外,正在使用 len(goodnessdict)合适的方法还是有更 Pythonic 的方法来打破循环?

最佳答案

根据您的评论:

rlist is arbitrarily long - if it has a length of ten, i'd want to iterate through it 10x (100 total attempts). if it has a length of 500, i'd want to process the first 100 items.

您正在寻找的是itertools.cycleitertools.islice:

for item in itertools.islice(itertools.cycle(rlist), iterations):
# do something with item from rlist

这将迭代 iterations 次,每次都从 rlist 中获取一个项目,如果到达列表末尾,则从头开始。

这是一个带有范围的示例:

for x in itertools.islice(itertools.cycle(range(4)), 10):
print(x)

这将打印:

0
1
2
3
0
1
2
3
0
1

关于python - 通过列表值迭代有限但任意次数的最Pythonic方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23715290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com