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))该文档读作
John : 1
Ben : 2
Josh : 3我该如何将它们按数字顺序进行排序,例如降序?
发布于 2015-12-03 19:34:17
你必须按数值排序,然后无论你得到什么结果,只要颠倒它就可以颠倒顺序。
这里的关键是按正确的事情进行排序,您需要通过定义一个函数来对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]发布于 2015-12-03 19:38:30
您需要在:处拆分每一行。删除名称中的空格,并将数字转换为整数(如果有,则转换为浮点数)。跳过空行。
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)))排序是直接的:
by_name = sorted(swag)
by_number = sorted(swag, key=lambda x: x[1])
by_number_descending = sorted(swag, key=lambda x: x[1], reverse=True)变化
使用itemgetter:
from operator import itemgetter
by_number_descending = sorted(swag, key=itemgetter(1), reverse=True)https://stackoverflow.com/questions/34064807
复制相似问题