根据值列表重复每个元素 [英] Repeat each elements based on a list of values

查看:51
本文介绍了根据值列表重复每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在一个Python内置函数,可根据另一个列表中的对应值重复一个列表的每个元素?例如,由于列表y中位置0处的值2,因此列表x位置0中的A重复了2次.

Is there a Python builtin that repeats each element of a list based on the corresponding value in another list? For example A in list x position 0 is repeated 2 times because of the value 2 at position 0 in the list y.

>>> x = ['A', 'B', 'C']
>>> y = [2, 1, 3]
>>> f(x, y)
['A', 'A', 'B', 'C', 'C', 'C']

或者换句话说,实现此操作的最快方法是什么?

Or to put it another way, what is the fastest way to achieve this operation?

推荐答案

以下是一种方法

x = ['A', 'B', 'C']
y = [2, 1, 3]

s = []
for a, b in zip(x, y):
    s.extend([a] * b)

print(s)

结果

['A', 'A', 'B', 'C', 'C', 'C']

这篇关于根据值列表重复每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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