-1

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

   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) 

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

4

3 回答 3

0

list.sort() 返回 Nome,因此变量 a 正在接收我这样固定的无值:

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']
于 2021-02-02T16:02:51.413 回答
0

除了@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) 
于 2021-02-02T16:08:31.780 回答
0

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) 
于 2021-02-02T16:13:36.583 回答