如何在Python中重复特定次数的单词?

3

通过使用两个列表

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

我希望能得到如下结果:

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

我尝试了word *次,但它不起作用。

5个回答

8
你可以使用带有zip的列表推导式:
word = ['wood', 'key', 'apple', 'tree']
times = [2,1,3,4]
result = [a for a, b in zip(word, times) for _ in range(b)]

输出:

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

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

print(np.repeat(word, times))

['木头' '木头' '钥匙' '苹果' '苹果' '苹果' '树' '树' '树' '树']


1
你需要以过程为导向思考,而不是进行某些数学/神奇的操作。换句话说,哪些步骤的序列会给我想要的结果。可能有简化的方法,但需要理解逻辑才能实现。
result = []
for i in range(0, len(words)):
    for t in range(0, times[i]):
            result.append(words[i])

0
你可以使用enumerate并循环遍历单词列表。
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']


0

使用itertools可以按照以下方式完成:

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)

使用集合可以如下实现:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接