Python重复列表到最大元素数

Pyl*_*der 5 python

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

拿这个:

list = ['one', 'two', 'three']
max_length = 7
Run Code Online (Sandbox Code Playgroud)

并产生这个:

final_list = ['one', 'two', 'three', 'one', 'two', 'three', 'one']
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 8

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

>>> from itertools import cycle, islice
>>> lst = [1, 2, 3]
>>> list(islice(cycle(lst), 7))
[1, 2, 3, 1, 2, 3, 1]
Run Code Online (Sandbox Code Playgroud)


Ste*_*ann 6

适当加减?

>>> lst = ['one', 'two', 'three']
>>> max_length = 7
>>> 
>>> q, r = divmod(max_length, len(lst))
>>> q * lst + lst[:r]
['one', 'two', 'three', 'one', 'two', 'three', 'one']
Run Code Online (Sandbox Code Playgroud)

对矿井和 mgilson 的解决方案进行基准测试,矿井看起来更有效,例如下面的测试矿井大约需要 0.7 秒,而 mgilson 的需要大约 2.8 秒。

from timeit import timeit
data = "lst = ['one', 'two', 'three'] * 1000; max_length = 12345678"

print(timeit('q, r = divmod(max_length, len(lst)); q * lst + lst[:r]',
             data,
             number=10))

print(timeit('list(islice(cycle(lst), max_length))',
             data + '; from itertools import cycle, islice',
             number=10))
Run Code Online (Sandbox Code Playgroud)