开发者

Fastest way to uniqify a list in Python

开发者 https://www.devze.com 2022-12-24 02:45 出处:网络
Fastest way to uniqify a list i开发者_高级运维n Python without preserving order? I saw many complicated solutions on the Internet - could they be faster than simply:

Fastest way to uniqify a list i开发者_高级运维n Python without preserving order? I saw many complicated solutions on the Internet - could they be faster than simply:

list(set([a,b,c,a]))


Going to a set only works for lists such that all their items are hashable -- so e.g. in your example if c = [], the code you give will raise an exception. For non-hashable, but comparable items, sorting the list, then using itertools.groupby to extract the unique items from it, is the best available solution (O(N log N)). If items are neither all hashable, nor all comparable, your only "last ditch" solution is O(N squared).

You can code a function to "uniquify" any list that uses the best available approach by trying each approach in order, with a try/except around the first and second (and a return of the result either at the end of the try clause, or, elegantly, in an else clause of the try statement;-).


set([a, b, c, a])

Leave it in that form if possible.


This updated post by Peter Bengtsson suggests two of the fastest ways to make a list of unique items in Python 3.6+ are:

# Unordered (hashable items)
list(set(seq))

# Order preserving
list(dict.fromkeys(seq))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号