2024-09-25 18:25:28 发布
网友
在python中,我已经有了单词列表和词干列表。如何创建一个字典,其中键是词干,值是带有该词干的单词列表,如下所示:
{‘achiev’: [‘achieved’, ‘achieve’] ‘accident’: [‘accidentally’, ‘accidental’] … }
您可以使用dict comprehnsion和list comprehnsion使用一行代码来实现这一点:
{stem: [w for w in words if w.startswith(stem)] for stem in stems}
stems = ['accident', 'achiev'] words = ['achieved', 'accidentally', 'achieve', 'accidental'] results = {} for stem in stems: stem_words = [w for w in words if w.startswith(stem)] results[stem] = stem_words print(results)
印刷品:
{'accident': ['accidentally', 'accidental'], 'achiev': ['achieved', 'achieve']}
您可以使用dict comprehnsion和list comprehnsion使用一行代码来实现这一点:
印刷品:
相关问题 更多 >
编程相关推荐