从python中的列表中获取唯一值

新手上路,请多包涵

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

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

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

原文由 savitha 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 228
1 个回答

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

 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)

正如已经指出的那样,集合不保持原始顺序。如果你需要,你应该寻找一个 有序的集合 实现(更多信息请参见 这个问题)。

原文由 lefterav 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题