从列表中删除重复和原始文件 - python [英] Remove duplicate and original from list - python

查看:150
本文介绍了从列表中删除重复和原始文件 - python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



,例如:
lst = ['a','b','c','c','c','d','e','e']



输出应该删除重复的
,所以这样的东西['a','b','d']



我不需要保留订单)

解决方案

使用 collections.Counter()对象,然后只保留计数为1的值:

 从集合导入计数器

[k for k,v in Counter(lst).iteritems()if v = = 1]

这是一个O(N)算法;您只需要循环遍历N个项目列表一次,然后循环遍历较少的项目(< N),以提取出现只有一次的值。



如果顺序是重要的,分开步骤:

 计数= Counter(lst)
[k for l in lst if [k] == 1]

演示:

 >>>从集合导入计数器
>>>> lst = ['a','b','c','c','c','d','e','e']
>>> [k for k,v in Counter(lst).iteritems()if v == 1]
['a','b','d']
>>> count = Counter(lst)
>>>> [k for k in lst if count [k] == 1]
['a','b','d']

这两种方法的顺序相同是巧合;其他输入可能会导致不同的顺序。


given a list of string (i am not aware of list), i want to remove the duplicate and original word.

for example: lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']

the output should should remove the duplicates so something like this ['a', 'b', 'd']

I do not need to preserve the order)

解决方案

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).iteritems() if v == 1]

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.

If order is important, separate the steps:

counts = Counter(lst)
[k for k in lst if counts[k] == 1]

Demo:

>>> from collections import Counter
>>> lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
>>> [k for k, v in Counter(lst).iteritems() if v == 1]
['a', 'b', 'd']
>>> counts = Counter(lst)
>>> [k for k in lst if counts[k] == 1]
['a', 'b', 'd']

That the order is the same for both approaches is a coincidence; other inputs may result in a different order.

这篇关于从列表中删除重复和原始文件 - python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆