首页 > 解决方案 > python:显示列表中的唯一元素

问题描述

我是这种 python 语言的新手:我在以下 pgm 中显示列表中的唯一元素时遇到问题:以下是我的程序:

def unique_list(lst):
    c = []
    for i in lst:
        if (lst.count(i)>=1) & i not in c:
            c.append(i)
            #print(c)
    return c  
print(unique_list([1,1,1,2,2,3,3,4,5]))

我收到的输出为:

[1,2,2,4]代替[1,2,3,4,5]

我认为 if stmt 中有一个错误……谁能解释一下我得到这个输出了吗?

标签: python-3.x

解决方案


您可以通过将列表转换为集合来获取列表中的唯一元素:

print(set([1,1,1,2,2,3,3,4,5]))

推荐阅读