从 python 中的列表中获取唯一值[重复]

2023-11-25

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

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

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


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

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)

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 python 中的列表中获取唯一值[重复] 的相关文章

随机推荐