基于dictionary numb创建重复字符串的列表/文本

2024-09-28 22:37:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下词典:

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'

Tags: 字符串文本列表字典数字mydict词典ber
2条回答

您可以只使用循环:

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

^{}库为此类情况提供了方便的功能:

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>)

相关问题 更多 >