作者:kingkongkoil | 来源:互联网 | 2023-10-11 17:05
这个想法是在每个不同的n
时间重复列表的元素,如下所示。
ls = [7, 3, 11, 5, 2, 3, 4, 4, 2, 3]
id_list_fname = ['S11', 'S15', 'S16', 'S17', 'S19', 'S3', 'S4', 'S5', 'S6', 'S9']
all_ls = []
for id, repeat in zip(id_list_fname, ls):
res = [ele for ele in[id] for i in range(repeat)]
all_ls.append(res)
因此,我希望结果是一个单一的平面列表,我实现如下。
def flatten(lst):
for item in lst:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
final_output = list(flatten(all_ls))
的输出final_output
:
['S11', 'S11', 'S11', 'S11', 'S11', 'S11', 'S11', 'S15', 'S15', 'S15',
'S16', 'S16', 'S16', 'S16', 'S16', 'S16', 'S16', 'S16', 'S16', 'S16',
'S16', 'S17', 'S17', 'S17', 'S17', 'S17', 'S19', 'S19', 'S3', 'S3',
'S3', 'S4', 'S4', 'S4', 'S4', 'S5', 'S5', 'S5', 'S5', 'S6', 'S6',
'S9', 'S9', 'S9']
但我想知道是否存在更紧凑的方法或技术,例如itertools
使用上面的代码片段实现重复元素。
回答
您可以使用itertools.chain
和itertools.repeat
from itertools import chain, repeat
ls = [7, 3, 11, 5, 2, 3, 4, 4, 2, 3]
id_list_fname = ['S11', 'S15', 'S16', 'S17', 'S19', 'S3', 'S4', 'S5', 'S6', 'S9']
res = list(chain.from_iterable(repeat(j, times = i) for i, j in zip(ls, id_list_fname)))
print(res)
输出
['S11', 'S11', 'S11', 'S11', 'S11', 'S11', 'S11', 'S15', 'S15', 'S15', 'S16', 'S16', 'S16', 'S16', 'S16', 'S16', 'S16', 'S16', 'S16', 'S16', 'S16', 'S17', 'S17', 'S17', 'S17', 'S17', 'S19', 'S19', 'S3', 'S3', 'S3', 'S4', 'S4', 'S4', 'S4', 'S5', 'S5', 'S5', 'S5', 'S6', 'S6', 'S9', 'S9', 'S9']