重复列表中的每个项目多次在另一个列表中指定 [英] Repeat each item in a list a number of times specified in another list

查看:43
本文介绍了重复列表中的每个项目多次在另一个列表中指定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表, x y :

>>> x = [2, 3, 4]
>>> y = [1, 2, 3]

我想用这些来创建一个新列表.新列表将使 x 中的每个元素重复由 y 中相应元素指定的次数.因此,所需的输出是

I want to use these to create a new list. The new list will have each element in x repeated the number of times specified by the corresponding element in y. Hence, the desired output is

>>> new_list
[2, 3, 3, 4, 4, 4]

new_list 中元素的顺序对我来说并不重要.成为 list 也是不重要的-任何序列类型都可以.

The order of the elements in new_list doesn't matter to me. It's also not crucial that it be a list -- any sequence type is fine.

什么是最快,最高效,最Pythonic的方式来实现这一目标?

What is the fastest, most efficient, most Pythonic way to achieve this?

推荐答案

numpy的 repeat 函数完成任务:

numpy's repeat function gets the job done:

>>> import numpy as np
>>> x = [2, 3, 4]
>>> y = [1, 2, 3]
>>> np.repeat(x, y)
array([2, 3, 3, 4, 4, 4])

这篇关于重复列表中的每个项目多次在另一个列表中指定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆