繁体   English   中英

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

[英]Create list / text of repeated strings based on dictionary number

我有以下字典:

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'

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

您可能只使用循环:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM