根据字典编号创建重复字符串的列表/文本



我有以下字典:

mydict = {'mindestens': 2,
'Situation': 3,
'österreichische': 2,
'habe.': 1,
'Über': 1,
}

我怎样才能从中获取列表/文本,当字典中的数字映射到它时,我的字典中的字符串是重复的:

mylist = ['mindestens', 'mindestens', 'Situation', 'Situation', 'Situation',.., 'Über']
mytext = 'mindestens mindestens Situation Situation Situation ... Über'

您可能只使用循环:

mylist = []
for word,times in mydict.items():
for i in range(times):
mylist.append(word)

itertools库在这种情况下具有方便的功能:

from itertools import chain, repeat
mydict = {'mindestens': 2, 'Situation': 3, 'österreichische': 2,
'habe.': 1, 'Über': 1,
}
res = list(chain.from_iterable(repeat(k, v) for k, v in mydict.items()))
print(res)

输出:

['mindestens', 'mindestens', 'Situation', 'Situation', 'Situation', 'österreichische', 'österreichische', 'habe.', 'Über']

对于文本版本 - 加入列表项是微不足道的:' '.join(<iterable>)

最新更新