简体   繁体   English

python列表中的不同值

[英]Distinct values in python list

I need to extract unique values in python list by omitting the repeated values altogether:我需要通过完全省略重复值来提取 python 列表中的唯一值:

Input:输入:

lis = ['a','l','f','a']

Desired Output:期望输出:

lis2 = ['l','f']

So I need to remove all duplicate iteams.所以我需要删除所有重复的项目。 Sets won't do cause I don't want 'a' in it集合不会做,因为我不想要 'a'

You basically want items which count in the list is only 1. Count of items in the list - use Counter class您基本上希望列表中的项目数仅为 1。列表中的项目数 - 使用Counter

from collections import Counter
lis = ['a','l','f','a']
counter = Counter(lis)
lis2 = [elem for elem in lis if counter[elem] == 1]
print(lis2)

You could also use list.count , but that would go through the list each time, giving you O(n^2) complexity, while creating the Counter is O(n) and then checking count is O(1) (n times), resulting in O(n) .你也可以使用list.count ,但每次都会遍历列表,给你O(n^2)复杂度,而创建 Counter 是O(n)然后检查 count 是O(1) (n 次) ,导致O(n)

this little function will create a dictionary of the number of occurrences of each element, then filter out the ones with multiple occurrences, and return the resulting list.这个小函数将创建每个元素出现次数的字典,然后过滤出多次出现的元素,并返回结果列表。

lst = ['a','b', 'c', 'a']

def removeDupes(lst):
    counts = {}
    for item in lst:
        if counts.get(item):
            counts[item] += 1
        else:
            counts[item] = 1
    result = dict({(k, v) for k, v in counts.items() if v == 1})
    return result.keys()

print(removeDupes(lst)) # outputs: ['b', 'c']

这是一个简单的衬垫!

lis2 = list(set(lis) - set([x for x in lis if lis.count(x) > 1])) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM