2017-01-22 69 views
0

發生了一件非常奇怪而奇怪的事情。我試圖在Compare 1 column of 2D array and remove duplicates Python回答這個問題,我做了以下的答案(我沒有張貼,因爲現存的一些答案,這個問題是很多緊湊和高效的),但是這是我做的代碼:來自相同代碼的Python不同結果

array = [['abc',2,3,], 
     ['abc',2,3], 
     ['bb',5,5], 
     ['bb',4,6], 
     ['sa',3,5], 
     ['tt',2,1]] 

temp = [] 
temp2 = [] 

for item in array: 
    temp.append(item[0]) 

temp2 = list(set(temp)) 

x = 0 
for item in temp2: 
    x = 0 
    for i in temp: 
     if item == i: 
      x+=1 
     if x >= 2: 
      while i in temp: 
       temp.remove(i) 

for u in array: 
    for item in array: 
     if item[0] not in temp: 
      array.remove(item) 

print(array) 

代碼應該工作,做給定的鏈接請求者。但我拿到兩雙成績:

[['sa', 3, 5], ['tt', 2, 1]] 

而且

[['bb', 4, 6], ['tt', 2, 1]] 

爲什麼同一個操作系統上同樣的代碼上同所有相同的編譯器產生兩個不同的答案時運行?注意:結果不會交替。在上面列出的兩個可能的輸出之間是隨機的。

+0

您正在迭代'temp'和'array',同時從中移除值。這是你想要的嗎? – ForceBru

+0

啊!謝謝@ForceBru。如果您發佈答案,我可以標記爲正確。 – Octo

回答

3

在Python集合中沒有任何特定的順序,即實現可以自由選擇任何順序,因此對於每個程序運行它都可能不同。

要轉換爲一組在這裏:

temp2 = list(set(temp)) 

訂購的結果應該給你一致的(但也許不是正確的)結果:

temp2 = sorted(set(temp)) 

我的結果array

排序:

temp2 = sorted(set(temp)) 

array看起來是這樣的:

[['bb', 4, 6], ['tt', 2, 1]] 

反轉:

temp2 = sorted(set(temp), reverse=True) 

array看起來是這樣的:

[['sa', 3, 5], ['tt', 2, 1]] 
相關問題