python - 如何只打印列表中的唯一项目,那些出现一次?

标签 python python-3.x

def get_distinct(original_list):
    distinct_list = []
    for i in original_list:
        if i not in distinct_list:
            distinct_list.append(each)
     return distinct_list

list_1 = [1,2,3,4,4,5,6,6]
print(get_distinct(list_1))

所以我希望它打印 1、2、3、5 而不是 1、2、3、4、5、6

最佳答案

collections.Counter()是计算事物的好方法,例如:

from collections import Counter

def get_distinct(original_list):
    return [k for k, v in Counter(original_list).items() if v == 1]

In []:
list_1 = [1,2,3,4,4,5,6,6]
get_distinct(list_1)

Out[]:
[1, 2, 3, 5]

虽然在 3.6 中,这将按照预期的顺序进行您可以创建一个 set 并使用它来测试唯一性,例如:

def get_distinct(original_list):
    uniqs = {k for k, v in Counter(original_list).items() if v == 1}
    return [e for e in original_list if e in uniqs]

关于python - 如何只打印列表中的唯一项目,那些出现一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50901119/

相关文章:

python - 拆分命令 - 选择输出名称

python - 发生异常 : TypeError:only size-1 arrays can be converted to Python scalars

python-3.x - "TypeError: a bytes-like object is required, not ' 海峡 '"。我怎样才能解决这个问题?

Python3 : Writing data of bytes in a file

python - 获取 "database error"(使用Django-nonrel的django、djangotoolbox、mongodbengine)

python - 如何用填充的 0 reshape Numpy 数组

python - 异常评估顺序

python-3.x - 为什么python说 "f"或 "q"未定义?

Python cx_Freeze __init__ "no module named codecs"

python - Django 模型字段如何与多个模型相关?