2017-10-18 23 views
0

我試圖找到類似於我現在要問的類似問題。但是,答案並沒有真正幫助我。我試圖獲得價值,但如果價值相同,只是一個價值。在這裏我的代碼:Python,如果值相同,只能得到一個值

第一,我有這樣的

ids_data = [] 
arr_rest_ids = [('8380128579', 309), ('8380128579', 311), ('8380128579', 310), ('8380222579', 313)] 

if arr_rest_ids: 
    for i in arr_rest_ids: 
     ids_data.append(i) 

我有狀態字符串和整數條件,病情告訴整數有一個值。我試圖創造一個條件,如果價值是相同的,只得到一個值。

我想要的結果是這樣的:

ids_data = [309, 313] 
arr_rest_ids = [('8380128579', 309), ('8380128579', 311), ('8380128579', 310), ('8380222579', 313)] 

if arr_rest_ids: 
    for i in arr_rest_ids: 
     ids_data.append(i) 

的ids_data變量顯示ID只是一個不同的值。

+0

是爲了重要?如果沒有,只需轉換爲'set'。 –

回答

2

最簡單的是維護一組您所看到的值:

arr_rest_ids = [('8380128579', 309), ('8380128579', 311), ('8380128579', 310), ('8380222579', 313)] 
ids_data = [] 
seen = set() 

# no check needed here. If arr_rest_ids is empty, the loop won't start 
for x, y in arr_rest_ids: 
    if x not in seen: 
     ids_data.append(y) 
     seen.add(x) 

在Python3,你也可以使用這個技巧來達到同樣在更少的行:

seen = set() 
ids_data = [seen.add(x) or y for x, y in arr_rest_ids if x not in seen] 
+0

非常感謝您爲我工作。但是,你能向我解釋爲什麼不需要檢查每一個值嗎?在我的邏輯,我必須檢查每一個值,以知道價值是否相同。 @schwobaseggl –

+0

@Scarlettstone你**做**用'x in seen'檢查每一個值,還是我誤解你? – schwobaseggl

+0

不,我試圖檢查使用'''爲我在arr_rest_ids j爲我'''' –

相關問題