从python列表中获取唯一值 [英] Get unique values from a list in python

查看:79
本文介绍了从python列表中获取唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to get the unique values from the following list:

['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)

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

is there a better solution I should use?

推荐答案

首先正确声明您的列表,并用逗号分隔.您可以通过将列表转换为集合来获得唯一值.

First declare your list properly, separated by commas. You can get the unique values by converting the list to a set.

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

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

If you use it further as a list, you should convert it back to a list by doing:

mynewlist = list(myset)

另一种可能更快的方法是从头开始使用集合而不是列表.然后您的代码应该是:

Another possibility, probably faster would be to use a set from the beginning, instead of a list. Then your code should be:

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

正如已经指出的那样,集合不保持原始顺序.如果需要,您应该寻找有序集实现(请参见

As it has been pointed out, sets do not maintain the original order. If you need that, you should look for an ordered set implementation (see this question for more).

这篇关于从python列表中获取唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆