2014-07-17 42 views
-2

我有一個重複數字的元組,並且只想保留唯一的項目但不更改順序。這工作:集合中的元組唯一元素在Python中更改順序

values = (30.0,30.0,30.0,15.0,30.0]) print set(values)

返回:

set([30.0, 15.0]) 

但是當我嘗試:

values = (2, 1, 2, 1) 

它返回:

set([1, 2]) 

我的問題是,爲什麼是不是在第二個例子中保留訂單。

+1

集沒有次序。 –

+0

正如@SimeonVisser所說的那樣,並沒有重複元素。 – Trimax

+0

重複的問題:http://stackoverflow.com/questions/9792664/python-set-changes-element-order?rq=1 – Yuan

回答

1

集沒有次序的概念,但你可以使用一個OrderedDict達到你想要的東西:

>>> from collections import OrderedDict 
>>> 
>>> values = (2, 1, 2, 1) 
>>> list(OrderedDict.fromkeys(values)) 
[2, 1] 
>>> 
>>> values = (30.0, 30.0, 30.0, 15.0, 30.0) 
>>> list(OrderedDict.fromkeys(values)) 
[30.0, 15.0] 
+0

謝謝。 @Simon Visser也。 – PhilL