Python | 程序以升序和降序对给定列表的元素进行排序

Given a list of the elements and we have to sort the list in Ascending and the Descending order in Python.

给定一个元素列表,我们必须按Python的升序和降序对列表进行排序。

Python list.sort()方法 (Python list.sort() Method)

sort() is a inbuilt method in Python, it is used to sort the elements/objects of the list in Ascending and Descending Order.

sort()是Python中的内置方法,用于按升序和降序对列表中的元素/对象进行排序。

Sorting elements in Ascending Order (list.sort())

升序排序元素(list.sort())

Syntax:

句法:

 list.sort()

Program to sort list elements in Ascending Order

程序以升序对列表元素进行排序

# List of integers
num = [10, 30, 40, 20, 50]

# sorting and printing 
num.sort()
print (num)

# List of float numbers
fnum = [10.23, 10.12, 20.45, 11.00, 0.1]

# sorting and printing
fnum.sort()
print (fnum)

# List of strings 
str = ["Banana", "Cat", "Apple", "Dog", "Fish"]

# sorting and  printing
str.sort()
print (str)

Output

输出量

    [10, 20, 30, 40, 50]
    [0.1, 10.12, 10.23, 11.0, 20.45]
    ['Apple', 'Banana', 'Cat', 'Dog', 'Fish']


Sorting in Descending Order (list.sort(reverse=True))

降序排序(list.sort(reverse = True))

To sort a list in descending order, we pass reverse=True as an argument with sort() method.

要按降序对列表进行排序,我们使用sort()方法将reverse = True作为参数传递。

Syntax:

句法:

 list.sort(reverse=True)

Program to sort list elements in Descending Order

程序以降序对列表元素进行排序

# List of integers
num = [10, 30, 40, 20, 50]

# sorting and printing 
num.sort(reverse=True)
print (num)

# List of float numbers
fnum = [10.23, 10.12, 20.45, 11.00, 0.1]

# sorting and printing
fnum.sort(reverse=True)
print (fnum)

# List of strings 
str = ["Banana", "Cat", "Apple", "Dog", "Fish"]

# sorting and  printing
str.sort(reverse=True)
print (str)

Output

输出量

    [50, 40, 30, 20, 10]
    [20.45, 11.0, 10.23, 10.12, 0.1]
    ['Fish', 'Dog', 'Cat', 'Banana', 'Apple']


翻译自: https://www.includehelp.com/python/sort-the-elements-of-given-list-in-ascending-and-descending-order.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值