简体   繁体   English

按字母和数字排序

[英]Sorting Alphabetically and Numerically

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))

The document reads as 该文件读为

John : 1
Ben : 2
Josh : 3

How would I go about ordering these into numerical order, such as descending? 我如何将它们按数字顺序排序,例如降序排列?

You have to sort by the numerical value, and then whatever result you get, simply reverse it to reverse the order. 您必须按数值排序,然后无论得到什么结果,只需将其反转即可反转顺序。

The key here is to sort by the right thing which you need to do by defining a function for the key argument to sorted. 此处的关键是通过定义要对key参数进行排序的函数,按照需要执行的正确操作进行排序。

Here the function is a lambda, which simply return the numeric part of the string to be sorted by; 这里的函数是一个lambda,它简单地返回要排序的字符串的数字部分; which will return it in ascending order. 它将以升序返回。

To reverse the order, simply reverse the list. 要颠倒顺序,只需颠倒列表即可。

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]

You need to split each line at the : . 您需要将每行的分裂: Remove white space from the names and convert the number into an integer (or float if you have). 从名称中删除空格,然后将数字转换为整数(如果有,则浮点数)。 Skip empty lines. 跳过空行。

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)))

Sorting is straight forward: 排序很简单:

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)

Variation 变异

Use itemgetter : 使用itemgetter

from operator import itemgetter

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM