List排序(升序和降序)



问题:以列表的形式从用户处获取输入,并按升序和降序排列列表中的元素

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) 

这是我尝试的代码,但它显示错误。你能帮帮我吗?

list.sort()返回name,因此变量a接收一个none值i固定如下:

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)

,这是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']

和字符串

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']

除了@John的答案,您应该将list重命名为其他东西,因为list已经被python用作类型。下面是一个例子:

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不返回排序列表;相反,它对列表进行排序。下面的代码运行良好

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) 

相关内容

  • 没有找到相关文章