重复列表的序列
Repeat a sequence of a list
问题
给定以下列表:
l=[1,2,3,4,5,6]
我想重复 n
列表的第一个元素 r
次,然后,对列表的下一个 n
元素执行相同的操作,依此类推...
例如,对于 n=2
和 r=2
:
result=[1,2,1,2,3,4,3,4,5,6,5,6]
对于n=3
和r=2
:
result=[1,2,3,1,2,3,4,5,6,4,5,6]
我的拙劣尝试
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)
我该如何改进这段代码? clean/efficient/good 更实用的做法是什么?
你可以像下面这样干净利落地实现。
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]
像这样的东西应该适合你:
l=[1,2,3,4,5,6]
n=3
r=2
result=[]
for i in range(0,len(l),n):
result += l[i:i+n]*r
或者作为一个函数:
def repeat_sequence(l, n, r):
result = []
for i in range(0,len(l),n):
result += l[i:i+n]*r
return result
l=[1,2,3,4,5,6]
repeat_sequence(l, 3, 2)
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))
问题
给定以下列表:
l=[1,2,3,4,5,6]
我想重复 n
列表的第一个元素 r
次,然后,对列表的下一个 n
元素执行相同的操作,依此类推...
例如,对于 n=2
和 r=2
:
result=[1,2,1,2,3,4,3,4,5,6,5,6]
对于n=3
和r=2
:
result=[1,2,3,1,2,3,4,5,6,4,5,6]
我的拙劣尝试
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)
我该如何改进这段代码? clean/efficient/good 更实用的做法是什么?
你可以像下面这样干净利落地实现。
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]
像这样的东西应该适合你:
l=[1,2,3,4,5,6]
n=3
r=2
result=[]
for i in range(0,len(l),n):
result += l[i:i+n]*r
或者作为一个函数:
def repeat_sequence(l, n, r):
result = []
for i in range(0,len(l),n):
result += l[i:i+n]*r
return result
l=[1,2,3,4,5,6]
repeat_sequence(l, 3, 2)
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))