python:显示列表中的唯一元素

时间:2018-07-11 07:50:25

标签: python-3.x

我是这种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中有一个错误...谁能解释我,我得到这个输出了吗?

1 个答案:

答案 0 :(得分:0)

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

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