这个想法是用每个不同的n时间重复list的元素,如下所示。
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,可以像我使用上面的代码片段实现的那样拥有repeat元素。
发布于 2021-01-31 14:30:23
就您的代码而言,在将项添加到all_ls中时,请使用list.extend()而不是list.append()。这会将列表中的项添加到现有列表,而不是将列表添加到现有列表。
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 s,repeat in zip(id_list_fname ,ls):
res = [ele for ele in [s] for i in range(repeat)]
all_ls.extend(res)输出
>>> all_ls
['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']一种更好的方法是使用列表理解--可以用一行代码来完成:
>>> [item for n,s in zip(ls, id_list_fname) for item in [s]*n]
['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']发布于 2021-01-31 14:29:33
您可以使用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']发布于 2021-02-04 21:49:34
Numpy有repeat函数:
np.repeat(id_list_fname, ls)如果你绝对需要一个列表:
np.repeat(id_list_fname, ls).tolist()如果您不想使用numpy,请记住python允许嵌套理解,这本质上是创建单个平面列表的多个for循环。你的原始循环可以写成一个简单的一行代码:
[id for id, repeat in zip(id_list_fname, ls) for _ in range(repeat)]https://stackoverflow.com/questions/65976317
复制相似问题