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

后端 未结 3 1669
野趣味
野趣味 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: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.

提交回复
热议问题