如何从di值的列表中删除短字符串

2024-09-29 23:17:57 发布

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

我想创建一个名为remove_short_synonyms()的函数,它通过dict传递 作为参数。参数dict的键是words和 相应的值是同义词列表。函数将删除所有 每个对应列表中少于7个字符的同义词 同义词。在

如果是这样的话:

synonyms_dict = {'beautiful': ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']}

我怎样才能得到这个作为输出?在

^{pr2}$

Tags: 函数列表参数prettydictremovesynonymsshort
3条回答

我认为你的问题的标题应该是从列表中删除值,而不是dict。在

可以使用remove、del或pop删除python列表中的元素。 Difference between del, remove and pop on lists

或者用一种更像Python的方式,我认为

dict['beautiful'] = [item for item in dict['beautiful'] if len(item)>=7]

利用听写理解和列表理解。在

synonyms_dict = {'beautiful' : ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']}
synonyms_dict = {k:[v1 for v1 in v if len(v1) >= 7] for k, v in synonyms_dict.items()}
print(synonyms_dict)

# {'beautiful': ['handsome', 'dazzling', 'splendid', 'magnificent']}

​

假设您有python>=3.x,对于初学者来说,更具可读性的解决方案是:

synonyms_dict = {'beautiful' : ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']}

new_list = []
for key,value in synonyms_dict.items():
   for i in range(len(value)):
      if len(value[i]) >= 7:
         new_list.append(value[i])

synonyms_dict['beautiful'] = new_list
print(synonyms_dict)

相关问题 更多 >

    热门问题