How to multiply a list of text by a list of integers and get one long list of text?

后端 未结 3 1661
野趣味
野趣味 2021-01-25 00:34

This is for Python 3. I have two lists:

lista = [\'foo\', \'bar\']
listb = [2, 3]

I\'m trying to get:

newlist = [\'foo\', \'foo         


        
3条回答
  •  迷失自我
    2021-01-25 01:04

    You were pretty close yourself! All you needed to do was use list.extend instead of list.append:

    new_list = []
    for i in zip(lista, listb):
        new_list.extend([i[0]] * i[1])
    

    this extends the list new_list with the elements you supply (appends each individual element) instead of appending the full list.

    If you need to get fancy you could always use functions from itertools to achieve the same effect:

    from itertools import chain, repeat
    
    new_list = list(chain(*map(repeat, lista, listb)))
    

    .extend in a loop, though slower, beats the previous in readability.

提交回复
热议问题