简体   繁体   中英

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.

Here the function is a lambda, which simply return the numeric part of the string to be sorted by; 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 :

from operator import itemgetter

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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