Python: Unique items of list in the order that it appears

半腔热情 提交于 2019-12-12 10:08:48

问题


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.


回答1:


This is an elegant way:

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).

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.




回答2:


l = []
for item in list_:
    if item not in l:
        l.append(item)

This gets slow for really big, diverse list_. In those cases, it would be worth it to also keep track of a set of seen values.



来源:https://stackoverflow.com/questions/39755464/python-unique-items-of-list-in-the-order-that-it-appears

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!