2016-10-31 48 views
0

我在這裏尋找一些幫助,我有一個列表,它也正是這個Python中刪除重複3在同一時間

名單如下:[1,1,1,5,5,5,10, 10,10,10,10,10,8,8,8,8,8,8]

希望的結果:[1,5,10,10,8,8]

我通過一次遍歷列表3來嘗試所有可能的方式,並且每三次更換一次。

''.join([List[i] for i in range(len(List) - 1) if List[i + 1] != XX[i]] + [List[-1]]) 

我只是不能得到我的頭附近有一些python嚮導誰可以做到這一點?

感謝

+0

的期望是什麼結果,這樣的名單= [1,1,1,1,1]? It – Alex

+6

在這種情況下,您只需要一個簡單的切片:「[1,1,1,5,5,10,10,10,10,10,10,8,8,8,8,8, 8] [:: 3]'。 – chepner

+0

會不會有重複? '[1,2,3]'會返回什麼? –

回答

7

嘗試

foo = [1, 1, 1, 5, 5, 5, 10, 10, 10, 10, 10, 10, 8, 8, 8, 8, 8, 8] 
print foo[::3] 

這就是所謂的 「名單切片」。這實際上做的是它從第一個開始列出你的列表的第三個參數。這篇文章Explain Python's slice notation更徹底地解釋了這個概念。

+0

工作!蟒蛇是驚人的謝謝 – NullOverFlow

+1

如果你滿意,你可以接受答案。謝謝。 – Hannu

1

代碼:

lst = [1, 1, 1, 5, 5, 5, 10, 10, 10, 10, 10, 10, 8, 8, 8, 8, 8, 8] 
output = [] 

skip = 0 
for idx, x in enumerate(lst): 
    if skip: 
     skip = skip - 1 
     continue 

    if (idx + 2) <= len(lst): 
     if lst[idx] == lst[idx+1] and lst[idx] == lst[idx+2]: 
      output.append(lst[idx]) 
      skip = skip + 2 
    else: 
     output.append(lst[idx]) 

print output