python – 在另一个嵌套列表中使用n重复嵌套列表中的元素

我有一个嵌套的列表,我希望通过在另一个嵌套列表(相同结构)中指定的给定次数重复每个元素来转换.

例:

phrases = [ ['Happy birthday to you','Happy birthday dear Einstein'],
            ['Happy birthday to you']
          ]

reps = [ [2, 1],
         [1]
       ]

#------- Desired output looks like:           -------------------------------------------
out = [ ['Happy birthday to you','Happy birthday to you','Happy birthday dear Einstein'],
        ['Happy birthday to you']
      ] 

通过列表理解使用嵌套循环,我尝试过:

[ [phrases[i][j] for rep in range(reps[i][j])] 
   for i in range(len(phrases)) 
     for j in range(len(phrases[i])) ]
#Returns:
#[['Happy birthday to you', 'Happy birthday to you'],
# ['Happy birthday dear Einstein'],
# ['Happy birthday to you']]

这不是我想要的.

最佳答案 您可以将
numpy.repeat与zip结合使用:

import numpy as np

res = [np.repeat(i, j).tolist() for i, j in zip(phrases, reps)]

# [['Happy birthday to you',
#   'Happy birthday to you',
#   'Happy birthday dear Einstein'],
#  ['Happy birthday to you']]
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞