'Repeat a sequence of a list [closed]
Problem
Given the following list:
l=[1,2,3,4,5,6]
I want to repeat the n first elements of the list r times, and after that, do the same for the next n elements of the list, and so on...
For example, for n=2 and r=2:
result=[1,2,1,2,3,4,3,4,5,6,5,6]
And for n=3 and r=2:
result=[1,2,3,1,2,3,4,5,6,4,5,6]
My clumsy attempt
l=[1,2,3,4,5,6]
n=3
r=2
l_new=[]
result=[]
for i in range(0,len(l),n):
reduced=l[i:(n+i)]
l_new.append(reduced)
for elem in l_new:
elem_new=elem*r
result+=(elem_new)
How can I improve this code? What is a more clean/efficient/good practice way of doing this?
Solution 1:[1]
def flatten(arr):
return [item for sublist in arr for item in sublist]
def flatmap(f, arr):
return flatten(map(f, arr))
def chunk(arr, r):
return [arr[i:i+r] for i in range(0,len(arr), r)]
def repeat_n_r_times(arr, n, r):
return flatmap(lambda x: x * n, chunk(arr, r))
Solution 2:[2]
you can achieve it cleanly as following.
l=[1,2,3,4,5,6]
def repeat_n_r_times(l, n, r):
list_breakdown = [l[i:i+n] for i in range(0, len(l), n)]
#make copies r times
lst = [lst*r for lst in list_breakdown]
# merge all sublist
return [item for sublist in lst for item in sublist]
print(repeat_n_r_times(l, 3, 2))
# OUTPUT: [1,2,3,1,2,3,4,5,6,4,5,6]
print(repeat_n_r_times(l, 2, 2))
# OUTPUT: result=[1,2,1,2,3,4,3,4,5,6,5,6]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | shivankgtm |
