简体   繁体   中英

Sort short_names in reverse alphabetic order

I dont understand what I am doing wrong:

Sort short_names in reverse alphabetic order. Sample output from given program:

['Tod', 'Sam', 'Joe', 'Jan', 'Ann']

My code:

short_names = ['Jan', 'Sam', 'Ann', 'Joe', 'Tod']

short_names.sort()

print(short_names)

sort函数有一个reverse选项:

short_names.sort(reverse=True)

As always, first have a look at the documentation for list.sort :

( *, key=None, reverse=None )

This method sorts the list in place, using only < comparisons between items.

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

So the items in your list will be sorted from "smallest" to "largest" using the < comparion, which for strings means lexicographical ordering (A < AB < B). To sort it in reverse order, use the reverse parameter:

short_names.sort(reverse=True)

For more information have a look at the official Sorting HOW TO .

short_names.sort()
short_names.reverse()

I'm doing this lab right now, and this is what your code should look like for the zybook, based on the methods we have learned.

user_input = input()
short_names = user_input.split()
short_names.sort()
short_names.reverse()
print(short_names)

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