JUNG UN LEE
JUNG UN LEE

Reputation: 35

how to repeat word specific times in 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.

Upvotes: 3

Views: 113

Answers (5)

Hetal Thaker
Hetal Thaker

Reputation: 717

Using itertools it can be done as below:

from itertools import chain, repeat
word = ['wood', 'key', 'apple', 'tree']
times = [2,1,3,4]
result = list(chain.from_iterable(map(repeat, word, times)))
print(result)

Using collections it can be done as below:

from collections import Counter
word = ['wood', 'key', 'apple', 'tree']
times = [2,1,3,4]
result = list(Counter(dict(zip(word,times))).elements())
print(result)

Upvotes: 0

programandoconro
programandoconro

Reputation: 2709

You can use enumerate and loop through the word list.

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

for i,w in enumerate(word):
    for _ in range(times[i]):
            results.append(w)

print(results)

# ['wood', 'wood', 'key', 'apple', 'apple', 'apple', 'tree', 'tree', 'tree', 'tree']

Upvotes: 0

Dan Roberts
Dan Roberts

Reputation: 4694

You need to think of it procedurally instead of some math/magical operation. In other words, what sequence of steps will give me the desired result. There may be ways to condense but need to understand logic to achieve.

result = []
for i in range(0, len(words)):
    for t in range(0, times[i]):
            result.append(words[i])

Upvotes: 1

Vons
Vons

Reputation: 3325

import numpy as np
word = ["wood", "key", "apple", "tree"]
times = [2,1,3,4]

print(np.repeat(word, times))

['wood' 'wood' 'key' 'apple' 'apple' 'apple' 'tree' 'tree' 'tree' 'tree']

Upvotes: 3

Ajax1234
Ajax1234

Reputation: 71461

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

Upvotes: 8

Related Questions