2021年4月30日星期五

How do you cycle a Python list to extend it from M to N values (M < N)?

I have a list of elements, N, that I want to run through repeatedly until it has M elements, where M can be any integer, not necessarily an integer multiple of N.

I found two ways to do this but neither seems as direct as I would expect is possible. Is there a more native way to do this in Python?

Here is what I came up with. Note that the first method was faster in limited testing.

from math import ceil    def repeat_list_1(values, n):      repeated = values * ceil(n / len(values))      return repeated[:n]  
from itertools import cycle    def repeat_list_2(values, n):      values_cycler = cycle(values)      repeated = [next(values_cycler) for _ in range(n)]      return repeated  
values = list(range(5))  n = 12  repeated1 = repeat_list_1(values, n)  repeated2 = repeat_list_2(values, n)  assert repeated1 == repeated2  print(repeated1)  [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2]  
https://stackoverflow.com/questions/67337527/how-do-you-cycle-a-python-list-to-extend-it-from-m-to-n-values-m-n May 01, 2021 at 12:41AM

没有评论:

发表评论