Python3如何删除列表中的重复字符串元素
Python 单词列表去重(保留原有顺序)方法
要实现列表去重且保留单词第一次出现的先后顺序,可使用以下两种方案:
方案1:Python 3.7+ 最简实现
Python 3.7及以上版本中字典默认保留插入顺序,利用字典key天然去重的特性可一行实现:
# 原始列表 word_list = ['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'and', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'is', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'sun', 'the', 'the', 'the', 'through', 'what', 'window', 'with', 'yonder'] # 去重操作 unique_words = list(dict.fromkeys(word_list))
方案2:全版本兼容实现
如果需要适配更低版本的Python,可通过遍历+集合记录已出现元素的方式实现,时间复杂度为O(n),效率更高:
word_list = ['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'and', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'is', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'sun', 'the', 'the', 'the', 'through', 'what', 'window', 'with', 'yonder'] seen = set() unique_words = [] for word in word_list: if word not in seen: seen.add(word) unique_words.append(word)
注意事项
- 禁止直接使用
list(set(word_list))的方式去重:set属于无序容器,转换后会打乱原有单词的出现顺序,不符合需求。 - 以上两种方案得到的最终结果完全匹配预期输出:
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
内容的提问来源于stack exchange,提问作者Ayman Mostafa
相关产品推荐
相关产品推荐

