2017-04-21 15 views
-2

嗨,我正在完成這項任務。Python提取列表更好分數

我想提取更好分數的列表中的一半(越小越好)。 例如:

s=[[1,2,3],[1,3,2],[2,1,3,[3,1,2],[3,2,1],[2,3,1]] 

列表S的相應的分數是

score=[13,14,24,28,17,17] 

我的願望輸出是: SS應該只包含3

ss =[[1,2,3],[1,3,2],[3,2,1]] 

ss =[[1,2,3],[1,3,2],[2,3,1]]。因爲最後兩個列表具有相同的比分

+2

問題是什麼? – brianpck

+0

評分列表背後的邏輯是什麼? – Arman

回答

0

嘗試:

[i for i, j in sorted(zip(s, score), key=lambda x: x[1])[:3]] 
+0

非常感謝! – user02

0

爲了實現這一點,你可以進行下面的步驟:

  1. 排序的scores升序排列的列表,並獲得最低n分數
  2. 取元素基於n最小號的出現在scores列表

下面的指數s名單是示例代碼通過u來實現它唱列表理解list.index(..)方法(步驟提到評論):

>>> s=[[1,2,3],[1,3,2],[2,1,3],[3,1,2],[3,2,1],[2,3,1]] 
>>> score=[13,14,24,28,17,17] 
>>> smallest_num_count = 3 # count of desired numbers 

# Get lowest three scores   v slice list from the start 
>>> smallest_scores = sorted(score)[:smallest_num_count] 
#     ^sorts the `score` list in ascending order 

#    v returns index of the first occurrence of the 
#    v `i` element in `score` lsit 
>>> [s[score.index(i)] for i in smallest_scores] 
[[1, 2, 3], [1, 3, 2], [3, 2, 1]] 
+0

非常感謝你 – user02