简体   繁体   中英

List Sorting (ascending and descending order)

Question: Get input from user in the form of list and arrange the elements of the list according to the ascending and descending order.

   list = eval(input("Enter the elements of the list")) 
   a = list.sort() 
   print("Sorted in ascending order: ", a) 
   d = list.sort(reverse = True) 
   print("Sorted in descending order: ", d) 

This is the code I tried, but it shows error. Can you please help me?

list.sort() return Nome, so the variable a is reciving a none value i fixed like this:

list = input("Enter the elements of the list, comma separate : ").split(',')
list.sort()
a = list
print("Sorted in ascending order: ", a) 
list.sort(reverse = True) 
b = list
print("Sorted in descending order: ", b)

and this was the result with int

Enter the elements of the list, comma separate : 1,7,8,9,7,5,4,6
Sorted in ascending order:  ['1', '4', '5', '6', '7', '7', '8', '9']
Sorted in descending order:  ['9', '8', '7', '7', '6', '5', '4', '1']

and with strings

Enter the elements of the list, comma separate : a,b,r,e,ra
Sorted in ascending order:  ['a', 'b', 'e', 'r', 'ra']
Sorted in descending order:  ['ra', 'r', 'e', 'b', 'a']

In addition to @John's answer, you should rename list to something else, since list is already in use by python as a type. Here's an example:

user_input = input("Enter the elements of the list, comma separated: ").split(',')
user_input.sort()
print("Sorted in ascending order: ", user_input) 
user_input.sort(reverse = True) 
print("Sorted in descending order: ", user_input) 

sort does not return the sorted list; rather, it sorts the list in place. The below code works fine

n = int(input("Enter number of elements : ")) 
a = list(map(int,input("\nEnter the numbers : ").strip().split()))[:n] 
b=sorted(a)
print("Sorted in ascending order: ", b) 
c = sorted(a,reverse = True) 
print("Sorted in descending order: ", c) 

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