Duplicate element in list x amount of times based off another list

Question:

I have a list of numbers and a list of strings

a = ['2', '2', '3', '4']
b = [' ', 'A', 'B', 'C']

I want to duplicate each string in b a times making my output look like:

[' ', ' ', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C']

I’ve tried using map a bunch of different ways. Also would this be easier to do if I just switched the lists to numpy arrays and dealing it with that package.

Asked By: theloosygoose

||

Answers:

To do this, just loop through the possible indexes and add the values to a list a number of times:

results = []
for i in range(len(b)):
    for _ in range(int(a[i])):
        results.append(b[i])

This can also be done through list comprehension for a more compact solution:

results = [b[i] for i in range(len(b)) for _ in range(int(a[i]))]
Answered By: KingsMMA

You can use a list comprehension, you will need to cast the string-version of your numbers to integers though using map(int, a).

[z for x,y in zip(map(int,a), b) for z in x*y]
Answered By: James

Due to the issues of differently-sized lists and zip(), I’d assert and write out a generator

def populate(a, b):
    assert len(a) == len(b), f"a(L{len(a)}) and b(L{len(b)}) must be the same length"
    for index in range(len(a)):
        for count in range(int(a[index])):
            yield b[index]
>>> a = ['2', '2', '3', '4']
>>> b = [' ', 'A', 'B', 'C']
>>> list(populate(a,b))
[' ', ' ', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C']
>>> b.append("D")
>>> list(populate(a,b))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in populate
AssertionError: a(L4) and b(L5) must be the same length
Answered By: ti7

Try this

MyList = []
For I in range(len(a)):
Num = int(a[I])
    For J in range(Num):
        MyList.append(b[I])
Print(MyList)

Sorry for weird formatting

Answered By: Sinister_7

An itertools solution:

from itertools import chain, repeat

a = ['2', '2', '3', '4']
b = [' ', 'A', 'B', 'C']

result = [*chain.from_iterable(map(repeat, b, map(int, a)))]

print(result)

Output (Try it online!):

[' ', ' ', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C']
Answered By: Kelly Bundy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.