[Python] Get unique values from a list

我有一個 array 想取出不重覆的項目。

解法1:

my_list = list(set(my_list))

上面解法,是很快,但 order 會亂掉。


Maintaining order:

# oneliners
# slow -> . --- 14.417 seconds ---
[x for i, x in enumerate(array) if x not in array[0:i]]

# fast -> . --- 0.0378 seconds ---
[x for i, x in enumerate(array) if array.index(x) == i]

# multiple lines
# fastest -> --- 0.012 seconds ---
uniq = []
[uniq.append(x) for x in array if x not in uniq]
uniq

Order doesn’t matter:

# fastest-est -> --- 0.0035 seconds ---
list(set(array))

相關文章

寫留言

你的電子郵件位址並不會被公開。 必要欄位標記為 *