列表推导式应用:合并二维列表中重复单词的多组释义 保证单词唯一
Python 单词多释义合并实现方案
实现思路
- 用字典作为临时存储结构,键为唯一单词,值为「单词 + 所有对应释义」的列表
- 遍历原始二维列表,遇到已存在的单词就把新释义追加到对应列表中,不存在就新建条目
- 最终提取字典所有值即可得到目标格式的结果
实现代码
# 示例输入 list_of_lists = [ ['absorption', 'a process in which one substance permeates another'], ['absorption', 'when radiated energy is retained on passing through a medium'], ['aerobic', 'depending on free oxygen or air'], ['aerobic', 'enhancing respiratory and circulatory efficiency'], ['chain reaction', 'a self-sustaining nuclear reaction'], ['chain reaction', 'a series of chemical reactions in which the product of one is a reactant in the next'] ] # 临时字典存储合并结果 word_dict = {} for word, definition in list_of_lists: # 单词不存在则新建条目,存在则追加释义 if word not in word_dict: word_dict[word] = [word] word_dict[word].append(definition) # 转成要求的输出格式 result = list(word_dict.values()) # 打印验证 for item in result: print(item)
运行输出
['absorption', 'a process in which one substance permeates another', 'when radiated energy is retained on passing through a medium'] ['aerobic', 'depending on free oxygen or air', 'enhancing respiratory and circulatory efficiency'] ['chain reaction', 'a self-sustaining nuclear reaction', 'a series of chemical reactions in which the product of one is a reactant in the next']
兼容说明
Python 3.7及以上版本默认字典会保留元素插入顺序,和单词首次出现的顺序完全一致;如果使用低于3.7的版本需要保序,可改用collections.OrderedDict实现:
from collections import OrderedDict word_dict = OrderedDict() for word, definition in list_of_lists: if word not in word_dict: word_dict[word] = [word] word_dict[word].append(definition) result = list(word_dict.values())
内容的提问来源于stack exchange,提问作者turineumann
相关产品推荐
相关产品推荐

