SELECT * FROM TABLE@dblink1
该文件为
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))
我如何将这些按顺序排序,例如降序?
答案 0 :(得分:1)
你必须按数值排序,然后根据你得到的结果,只需将其反转以反转顺序。
这里的关键是通过定义要排序的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]
答案 1 :(得分: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)))
排序很简单:
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)