简体   繁体   English

Python:列表的唯一项按其出现的顺序排列

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

In Python, we can get the unique items of a list L by using set(L) .在 Python 中,我们可以使用set(L)获取列表L的唯一项。 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 they appear in the list?有没有一种优雅的方法可以按照它们在列表中出现的顺序获取独特的项目?

If all of the items in the list are hashable , then a dictionary can be used for an order-preserving dedupe:如果列表中的所有项目都是hashable ,则可以使用字典进行保留顺序的重复数据删除:

L = list(dict.fromkeys(L))

For older Python versions (<= 3.6) where the standard dict is not order preserving, you can do the same thing using a collections.OrderedDict .对于标准 dict 不保留顺序的旧 Python 版本 (<= 3.6),您可以使用collections.OrderedDict执行相同的操作。

If any of the list items are unhashable, there will be a TypeError .如果任何列表项不可散列,则会出现TypeError You can use an alternative approach in this case, at the price of poorer performance.在这种情况下,您可以使用另一种方法,但代价是性能较差。 I refer you to the answer from Patrick Haugh .我建议您参考Patrick Haugh 的回答

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

This gets slow for really big, diverse list_ .对于非常大、多样化的list_ ,这会变得很慢。 In those cases, it would be worth it to also keep track of a set of seen values.在这些情况下,跟踪一组可见值也是值得的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM