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

时间:2018-03-13 15:12:24

标签: python list-comprehension

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

示例:

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']]

这不是我想要的。

2 个答案:

答案 0 :(得分:4)

您可以使用zip

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

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

new_data = [[i for b in [[c]*d for c, d in zip(a, b)] for i in b] for a, b in zip(phrases, reps)]

输出:

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

答案 1 :(得分:3)

您可以将numpy.repeatzip结合使用:

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']]