0

I have the following piece of code, with the goal of repeating every element of a 2D list a certain number of times:

empty =[]
l = [[1,2,3], [4,5,6]]
n = [2,3]
for i, _as in enumerate(l):
    for _a in _as:
        for _n in range(n[i]):
            empty.append(_a)

empty
> [1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]

I would like to try and write this in a single line list comprehension format.

I have made an attempt using using:

empty = [
         [
           [_a]*n[i] for _a in _as
         ] 
         for i, _as in enumerate(l) 
        ]

empty
> [[[1, 1], [2, 2], [3, 3]], [[4, 4, 4], [5, 5, 5], [6, 6, 6]]]

How may I correct the above code to provide the desired result?

Jack Rolph
  • 587
  • 5
  • 15
  • Does this answer your question? [Repeating elements of a list n times](https://stackoverflow.com/questions/24225072/repeating-elements-of-a-list-n-times) – taha Jul 04 '20 at 16:16

3 Answers3

5

if you're just looking to convert your code into a list comprehension then just write your loops in their original order. This way you'll never forget how to get things done using list comprehension.

output = [
    _a
    for i, _as in enumerate(l)
    for _a in _as
    for _n in range(n[i])
]
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
0

You can use a double list comprehension:

l = [[1,2,3], [4,5,6]]
n = [2, 3]
empty =[i for j in [[a]*f for b,f in zip(l,n) for a in b] for i in j]
print(empty)

Output:

[1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]
Red
  • 26,798
  • 7
  • 36
  • 58
0

You could use itertools.repeat to repeat the elements of each sublist with n, then itertools.chain.from_iterable to flatten the final list:

>>> from itertools import chain, repeat
>>> l = [[1,2,3], [4,5,6]]
>>> ns = [2, 3]
>>> list(chain.from_iterable(repeat(x, n) for lst, n in zip(l, ns) for x in lst))
[1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75