gpt4 book ai didi

python - 重复列表到最大元素数

转载 作者:太空狗 更新时间:2023-10-30 00:34:40 25 4
gpt4 key购买 nike

将列表重复到最大元素长度的最有效方法是什么?

拿这个:

lst = ['one', 'two', 'three']
max_length = 7

并产生这个:

final_list = ['one', 'two', 'three', 'one', 'two', 'three', 'one']

另见 How to replicate array to specific length array用于特定于 Numpy 的方法。

另见 Circular list iterator in Python用于对此类数据进行惰性迭代。

最佳答案

我可能会使用 iterools.cycleitertools.islice:

>>> from itertools import cycle, islice
>>> lst = [1, 2, 3]
>>> list(islice(cycle(lst), 7))
[1, 2, 3, 1, 2, 3, 1]

关于python - 重复列表到最大元素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39863250/

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