从python列表中获取唯一值

发布于 2021-02-02 23:18:15

我想从以下列表中获取唯一值:

['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']

我需要的输出是:

['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']

此代码有效:

output = []
for x in trends:
    if x not in output:
        output.append(x)
print(output)

我应该使用更好的解决方案吗?

关注者
0
被浏览
78
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    首先正确声明你的列表,以逗号分隔。你可以通过将列表转换为一组来获得唯一值。

    mylist = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
    myset = set(mylist)
    print(myset)
    

    如果进一步将其用作列表,则应执行以下操作将其转换回列表:

    mynewlist = list(myset)
    

    另一种可能(可能更快)的可能性是从头开始使用集合而不是列表。然后你的代码应为:

    output = set()
    for x in trends:
        output.add(x)
    print(output)
    

    正如已经指出的那样,集合不保持原始顺序。如果需要,则应查找有序集合实现



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看