2
[ 
[0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02], 
[0.02, 0.02, 0.015], 
[0.026, 0.026, 0.02, 0.02, 0.02, 0.015], 
[0.021, 0.021, 0.02, 0.017], [0.077, 0.076, 0.074, 0.055, 0.045, 0.021], 
[0.053, 0.052, 0.051, 0.023, 0.022], 
[0.016, 0.016] 
] 

以上是list,data ['stock']列表的輸出。列表清單中的重複刪除

我正在考慮刪除每個子列表中的重複內容,但無法找到一種方法來做到這一點。如果你看第3行,你會注意到有三個元素(0.02,0.02和0.015)。但是,前兩個元素實際上是重複的,因此其中一個元素是多餘的。

有沒有一種方法可以在每個子列表中執行檢查以在保留訂單的同時擺脫重複值?

請指教!

回答

3

貌似子列表已經排序,這樣你就可以申請itertools.groupby

In [1]: data = [ 
    ...: [0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02], 
    ...: [0.02, 0.02, 0.015], 
    ...: [0.026, 0.026, 0.02, 0.02, 0.02, 0.015], 
    ...: [0.021, 0.021, 0.02, 0.017], [0.077, 0.076, 0.074, 0.055, 0.045, 0.021], 
    ...: [0.053, 0.052, 0.051, 0.023, 0.022], 
    ...: [0.016, 0.016] 
    ...: ] 

In [2]: from itertools import groupby 

In [3]: [[k for k, g in groupby(subl)] for subl in data] 
Out[3]: 
[[0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02], 
[0.02, 0.015], 
[0.026, 0.02, 0.015], 
[0.021, 0.02, 0.017], 
[0.077, 0.076, 0.074, 0.055, 0.045, 0.021], 
[0.053, 0.052, 0.051, 0.023, 0.022], 
[0.016]] 
+0

+1。美麗列弗。 Python Rocks :) – Yavar

+0

太棒了! –

+0

'[k for k,g in groupby(subl)]'dup-removal應該被添加到'itertools.receipes'。不過,我不會對此投票,因爲我反對回答作者甚至沒有嘗試自行解決問題的問題。 – martineau

1

一個解決方案使用OrderedDict。這兩個連續和非連續的重複工作,同時保持順序

>>> from collections import OrderedDict 
>>> some_list = [ 
[0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02], 
[0.02, 0.02, 0.015], 
[0.026, 0.026, 0.02, 0.02, 0.02, 0.015], 
[0.021, 0.021, 0.02, 0.017], [0.077, 0.076, 0.074, 0.055, 0.045, 0.021], 
[0.053, 0.052, 0.051, 0.023, 0.022], 
[0.016, 0.016] 
] 
>>> [OrderedDict.fromkeys(e).keys() for e in some_list] 
[[0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02], [0.02, 0.015], [0.026, 0.02, 0.015], [0.021, 0.02, 0.017], [0.077, 0.076, 0.074, 0.055, 0.045, 0.021], [0.053, 0.052, 0.051, 0.023, 0.022], [0.016]] 
0

簡單前面回答:

使用名單(套(your_list))。

Set創建獨特的元素,list()將它轉換爲列表。

>>> lis1 = [1,2,3,4,4,3,2] 
>>> print list(set(lis1)) 
[1, 2, 3, 4] 
>>>