如何在python中重复单词特定时间?

通过使用 2 个列表

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

我想做出以下结果。

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

我试过word * times不行。

回答

您可以使用列表理解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']


以上是如何在python中重复单词特定时间?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>