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

查看:51
本文介绍了从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天全站免登陆