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

后端 未结 3 1630
野趣味
野趣味 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 00:49

    Use .extend() rather than .append().

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-25 01:08

    You can use list comprehension with the following one liner:

    new_list = [x for n,x in zip(listb,lista) for _ in range(n)]
    

    The code works as follows: first we generate a zip(listb,lista) which generates tuples of (2,'foo'), (3,'bar'), ... Now for each of these tuples we have a second for loop that iterates n times (for _ in range(n)) and thus we add x that many times to the list.

    The _ is a variable that is usually used to denote that the value _ carries is not important: it is only used because we need a variable in the for loop to force iteration.

    0 讨论(0)
提交回复
热议问题