2 回答

TA贡献1854条经验 获得超8个赞
第一步可能是创建一个嵌套列表,将每个2元素添加到一个新的子列表中:
from itertools import chain
from operator import itemgetter
i = [([0.2,0.10]),0.69, ([0.3,0.67]),0.70, ([0.5,0.68]),0.70, ([0.3,0.67]),0.65]
l = [i[x:x+2] for x in range(0, len(i),2)]
# [[[0.2, 0.1], 0.69], [[0.3, 0.67], 0.7], [[0.5, 0.68], 0.7], [[0.3, 0.67], 0.65]]
然后按每个子列表中的第二个元素对嵌套列表进行排序operator.itemgetter,并使用itertools.chain来展平结果:
list(chain(*sorted(l, key = itemgetter(1), reverse=True)))
[[0.3, 0.67], 0.7, [0.5, 0.68], 0.7, [0.2, 0.1], 0.69, [0.3, 0.67], 0.65]

TA贡献1829条经验 获得超7个赞
使用 zip 和 lambda 排序键排序的另一种方法:
首先,使用 zip 将您的“第三个位置”放入带有第一个和第二个数字的元组中:
output = list(zip(output[::2], output[1::2]))
#[([0.3, 0.67], 0.7), ([0.5, 0.68], 0.7), ([0.2, 0.1], 0.69), ([0.3, 0.67], 0.65)]
然后排序,使用您的第三个数字(在元组中它位于位置 2)作为排序键:
output.sort(key = lambda x: x[1])
#[([0.3, 0.67], 0.65), ([0.2, 0.1], 0.69), ([0.3, 0.67], 0.7), ([0.5, 0.68], 0.7)]
添加回答
举报