基于另一个列表中的元素重复一个列表中的元素 [英] Repeat elements in one list based on elements from another

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

问题描述

鉴于以下列表:

a = [0, 5, 1]
b = [1, 2, 1]

我想通过 [b] 中相应位置的编号重复 [a] 的每个元素以产生此:

I'd like to repeat each element of [a] by the number of its corresponding position in [b] to produce this:

[0, 5, 5, 1]

即0出现1次,5出现2次,1出现1次.

i.e. 0 occurs 1 time, 5 occurs 2 times, and 1 occurs 1 time.

推荐答案

In [7]: a = [0, 5, 1]

In [8]: b = [1, 2, 1]

In [9]: list(itertools.chain(*(itertools.repeat(elem, n) for elem, n in zip(a, b))))
Out[9]: [0, 5, 5, 1]

In [10]: b = [2, 3, 4]

In [11]: list(itertools.chain(*(itertools.repeat(elem, n) for elem, n in zip(a, b))))
Out[11]: [0, 0, 5, 5, 5, 1, 1, 1, 1]

这里的部分如下:

  • itertools.repeat(elem, n) - 重复 elem n 次
  • zip(a, b) 从两个列表中创建一个 2 元组列表,将每个元素与另一个列表中的相应元素配对.这正是您需要在用例中传递给 itertools.repeat 的内容.
  • itertools.chain - 将生成的迭代器列表扁平化为单个值列表.您可以像我那样使用 chain(*iterable) 或像 Martijn Peters 那样使用 chain.from_iterable(iterable).
  • itertools.repeat(elem, n) - repeat elem n times
  • zip(a, b) Make a list of 2-tuples out of the two lists, pairing each element with the corresponding element in the other list. This gives you exactly what you need to pass to itertools.repeat in your use case.
  • itertools.chain - flattens the resulting list of iterators into a single list of values. You can either chain(*iterable) as I have done or chain.from_iterable(iterable) as Martijn Peters does.

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

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