C8H10N4O2
C8H10N4O2

Reputation: 19005

Repeat elements in nested list with n in another nested list

I have a nested list of something that I would like to transform by repeating each element a given number of times specified in another nested list (of identical structure).

Example:

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

Using a nested loop via a list comprehension, I have tried:

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

Which is not quite what I want.

Upvotes: 3

Views: 285

Answers (2)

jpp
jpp

Reputation: 164653

You can use numpy.repeat combined with zip for this:

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

Upvotes: 3

Ajax1234
Ajax1234

Reputation: 71451

You can use 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)]

Output:

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

Upvotes: 4

Related Questions