Python:按显示顺序排列的列表的唯一项 [英] Python: Unique items of list in the order that it appears

查看:265
本文介绍了Python:按显示顺序排列的列表的唯一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我们可以使用set(list)获得列表的唯一项.但是,这样做会破坏值在原始列表中出现的顺序.是否有一种优雅的方法可以按其在列表中出现的顺序来获取唯一项.

In Python, we can get the unique items of the list using set(list). However doing this breaks the order in which the values appear in the original list. Is there an elegant way to get the unique items in the order in which it appears in the list.

推荐答案

这是一种优雅的方式:

from collections import OrderedDict
list(OrderedDict.fromkeys(list))

如果列表项都是可散列的,则它起作用(如果将其转换为集合而不触发异常,您将知道所有列表项都是可散列的).

It works if the list items are all hashable (you will know that all the list items are hashable if converting it to a set did not trigger an exception).

如果有任何项目不可散列,则有一个替代方案,以性能较差为代价,因此更健壮:我请您参考 answer 来自Patrick Haugh.

If any items are not hashable, there's an alternative which is more robust at the price of poorer performance: I refer you to the answer from Patrick Haugh.

这篇关于Python:按显示顺序排列的列表的唯一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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