当我混合使用整数和字符串时,如何将元素列表按数字顺序排序?

2024-09-30 18:30:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想订购一个包含整数和字符串的元素列表。我想把这张单子排在第一位,以便最大的分数排在第一位。你知道吗

列表如下所示:

winners = ["13, John", "8, Max", "15, Smith", "4, Bob"]

我尝试过用以下方法对列表进行反向排序:

winners.sort(reverse = True)

然而,这并没有奏效

我希望清单是:

winners = ["15, Smith", "13, John", "8, Max", "4, Bob"]

Tags: 方法字符串元素列表排序整数sortjohn
2条回答

a list of elements which contain both integers and strings

您没有这样的列表;您的列表包含字符串,而这些字符串恰好包含逗号分隔的值对,因此第一个值是整数的字符串表示形式。你知道吗

我们可以很容易地编写一个函数,解析其中一个字符串以生成相应的对(元组):

def parse(item):
    x, y = item.split(',')
    return int(x), y

然后我们可以使用它来根据这种解析的结果对列表进行排序,方法是使用内置sortkey参数:

winners.sort(reverse=true, key=parse)
winners = ["13, John", "8, Max", "15, Smith", "4, Bob"]

# Use function key to control sort order
winners.sort(reverse=True, key=lambda x: int(x.split(',')[0]))
print(winners) # Result ['15, Smith', '13, John', '8, Max', '4, Bob']

相关问题 更多 >