2016-10-04 4 views
2

最大要素長までリストを繰り返す最も効率的な方法は何ですか?Pythonリピートリストから最大要素数

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

そして、この生成します:これを取るために

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

答えて

6

を私はおそらくiterools.cycleitertools.isliceを使用したい:

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

私はいつもitertoolsを見てください。魅力のように動作します。 – Pylander

2

乗算適切?

>>> 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'] 

Benchmarkedに鉱山とmgilsonのソリューションは、鉱山はmgilsonのは、約2.8秒かかりながら、以下の試験採掘のための例えば約0.7秒かかり、より効率的に見えます。

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)) 
関連する問題