Repeat each item in a list a number of times specified in another list

后端 未结 4 1410
情歌与酒
情歌与酒 2020-12-03 23:59

I have two lists, x and y:

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

I want to use these to create a

4条回答
  •  余生分开走
    2020-12-04 00:10

    One way to achieve this is via using .elements() function of collections.Counter() along with zip. For example:

    >>> from collections import Counter
    
    >>> x = [2, 3, 4]
    >>> y = [1, 2, 3]
    
    # `.elements()` returns an object of `itertool.chain` type, which is an iterator.
    # in order to display it's content, here type-casting it to `list` 
    >>> list(Counter(dict(zip(x,y))).elements())
    [2, 3, 3, 4, 4, 4]
    

提交回复
热议问题