Remove duplicates and original from list(从列表中删除重复项和原始项)
问题描述
给定一个字符串列表,我想删除重复的单词和原始单词.
Given a list of strings I want to remove the duplicates and original word.
例如:
lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
输出应删除重复项,所以像这样 ['a', 'b', 'd']
The output should have the duplicates removed,
so something like this ['a', 'b', 'd']
我不需要保留订单.
推荐答案
使用 collections.Counter() object,然后只保留那些计数为 1 的值:
Use a collections.Counter() object, then keep only those values with a count of 1:
from collections import counter
[k for k, v in Counter(lst).items() if v == 1]
这是一个 O(N) 算法;您只需要遍历 N 个项目的列表一次,然后再对更少的项目 (< N) 进行第二次循环,以提取那些只出现一次的值.
This is a O(N) algorithm; you just need to loop through the list of N items once, then a second loop over fewer items (< N) to extract those values that appear just once.
如果顺序很重要并且您正在使用 Python <3.6、分离步骤:
If order is important and you are using Python < 3.6, separate the steps:
counts = Counter(lst)
[k for k in lst if counts[k] == 1]
演示:
>>> from collections import Counter
>>> lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
>>> [k for k, v in Counter(lst).items() if v == 1]
['a', 'b', 'd']
>>> counts = Counter(lst)
>>> [k for k in lst if counts[k] == 1]
['a', 'b', 'd']
两种方法的顺序相同是巧合;对于 Python 3.6 之前的 Python 版本,其他输入可能会导致不同的顺序.
That the order is the same for both approaches is a coincidence; for Python versions before Python 3.6, other inputs may result in a different order.
在 Python 3.6 中,字典的实现发生了变化,现在保留了输入顺序.
In Python 3.6 the implementation for dictionaries changed and input order is now retained.
这篇关于从列表中删除重复项和原始项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从列表中删除重复项和原始项
基础教程推荐
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
