通过使用两个列表
word = [wood, key, apple, tree]
times = [2,1,3,4]
我希望能得到如下结果:
result = [wood, wood, key, apple, apple, apple, tree, tree, tree, tree]
我尝试了word *次
,但它不起作用。
通过使用两个列表
word = [wood, key, apple, tree]
times = [2,1,3,4]
我希望能得到如下结果:
result = [wood, wood, key, apple, apple, apple, tree, tree, tree, tree]
我尝试了word *次
,但它不起作用。
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']
import numpy as np
word = ["wood", "key", "apple", "tree"]
times = [2,1,3,4]
print(np.repeat(word, times))
['木头' '木头' '钥匙' '苹果' '苹果' '苹果' '树' '树' '树' '树']
result = []
for i in range(0, len(words)):
for t in range(0, times[i]):
result.append(words[i])
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']
使用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)