سؤال

What I have:

names = ["Bob", "Dora", "Kelly"]
numbers = [5, 3, 2]

What I need:

list1 = ["Bob", "Bob", "Bob", "Bob", "Bob", "Dora", "Dora", "Dora", "Kelly", "Kelly"]

Such that their names are appended to a new list times i number of times as indicated by my numbers list.

هل كانت مفيدة؟

المحلول

Use zip() and a list comprehension:

[name for name, count in zip(names, numbers) for _ in range(count)]

zip() pairs up each name with each number, the list comprehension uses a nested set of for loops to repeat name the right number of times.

Demo:

>>> names = ["Bob", "Dora", "Kelly"]
>>> numbers = [5, 3, 2]
>>> [name for name, count in zip(names, numbers) for _ in range(count)]
['Bob', 'Bob', 'Bob', 'Bob', 'Bob', 'Dora', 'Dora', 'Dora', 'Kelly', 'Kelly']
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top