Python中使用过的元组解包,无法找出逻辑错误

问题描述 投票:0回答:1

似乎无法在这里解决问题:

我正在传递列表

vote_sort([("TOD",12),("Football",20),("Baseball",19),("Tennis",10)])

我得到的输出

[('Baseball', 19), ('Football', 20), ('TOD', 12), ('Tennis', 10)]

所需的输出:

[('Football', 20), ('Baseball', 19), ('TOD', 12), ('Tennis', 10)]

感谢您的帮助!

def vote_sort(ls):
    firstIndex = -1
    for a, b in ls:
        # EXTRACT THE VOTES = b
        firstIndex += 1
        for index in range(firstIndex+1, len(ls)):
            # COMPARISON,SORT AND SWAP
            if ls[index][1] > b:
                temp = ls[index]
                ls[index] = ls[firstIndex]
                ls[firstIndex] = temp 
    print(ls)

vote_sort([("TOD",12),("Football",20),("Baseball",19),("Tennis",10)])
python python-3.x sorting iterable-unpacking
1个回答
1
投票
print(sorted(input, key=lambda input: input[1], reverse=True))

输出:

[('Football', 20), ('Baseball', 19), ('TOD', 12), ('Tennis', 10)]
© www.soinside.com 2019 - 2024. All rights reserved.