具有更好分数的Python提取列表
嗨,我正在做这个任务 我想精确地提取列表中得分越高(越小越好)的一半。 例如:具有更好分数的Python提取列表,python,sorting,Python,Sorting,嗨,我正在做这个任务 我想精确地提取列表中得分越高(越小越好)的一半。 例如: 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]]。由于最后两个列表的得分相同,因此您可以执行以下步骤: 按升序排列分数列表,并获得
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]]
。由于最后两个列表的得分相同,因此您可以执行以下步骤:
分数列表
,并获得最低的n
分数n
分数列表中最小数字的出现索引,从s
列表中提取元素
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]]
[i for i, j in sorted(zip(s, score), key=lambda x: x[1])[:3]]