问题
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