按字母和数字排序

2024-05-15 09:05:18 发布

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

f = open(document) #this will open the selected class data
swag = [f.readline(),f.readline(),f.readline(),f.readline(),f.readline(),f.readline()] #need to make go on for amount of line

viewfile = input("Do you wish to view the results?")#This will determine whether or not the user wishes to view the results
if viewfile == 'yes': #If the users input equals yes, the program will continue
order = input("What order do you wish to view to answers? (Alphabetical)") #This will determine whether or not to order the results in alphabetical order
if order == 'Alphabetical' or 'alphabetical':
    print(sorted(swag))
if order == 'Top' or 'top':
    print(sorted(swag, key=int))

文件内容如下

^{pr2}$

我该如何按数字顺序排序,比如降序?在


Tags: orthetoyouviewinputreadlineif
2条回答

你必须按数值排序,然后不管你得到什么结果,只要把它颠倒过来就行了。在

这里的关键是通过为key参数定义一个要排序的函数,来按您需要做的正确事情进行排序。在

这里的函数是lambda,它只返回要排序的字符串的数字部分;它将按升序返回它。在

要颠倒顺序,只需颠倒列表。在

with open(document) as d:
   swag = [line.strip() for line in d if line.strip()]

by_number = sorted(swag, key=lambda x: int(x.split(':')[1]))
descending = by_number[::-1]

您需要在:处拆分每一行。从名字中去掉空格,并将数字转换成整数(或者浮点型,如果有的话)。跳过空行。在

with open(document) as fobj:
    swag = []
    for line in fobj:
        if not line.strip():
            continue
        name, number_string = line.split(':')
        swag.append((name.strip(), int(number_string)))

排序是直接进行的:

^{pr2}$

变化

使用itemgetter

from operator import itemgetter

by_number_descending = sorted(swag, key=itemgetter(1), reverse=True)

相关问题 更多 >