Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to repeat word specific times in python?

Tags:

python

by using 2 lists

word = [wood, key, apple, tree]
times = [2,1,3,4]

I want to make as a below result.

result = [wood, wood, key, apple, apple, apple, tree, tree, tree, tree]

i tried word * times it doesn't work.

like image 746
JUNG UN LEE Avatar asked May 08 '26 02:05

JUNG UN LEE


1 Answers

You can use a list comprehension with zip:

word = ['wood', 'key', 'apple', 'tree']
times = [2,1,3,4]
result = [a for a, b in zip(word, times) for _ in range(b)]

Output:

['wood', 'wood', 'key', 'apple', 'apple', 'apple', 'tree', 'tree', 'tree', 'tree']
like image 180
Ajax1234 Avatar answered May 10 '26 14:05

Ajax1234



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!