[英]How to repeat each of a Python list's elements n times with itertools only?
[英]How to repeat list's elements with each different n times and in Python?
这个想法是重复列表的元素,每个不同的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 的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)
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']
关于您的代码,在将项目添加到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)
Output
>>> 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']
Numpy 有repeat
function:
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.