新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python對列表進行永久性或臨時排序的方法

python對列表進行永久性或臨時排序的方法
1、對列表進行永久性排序:使用方法 sort()
sort() 方法:用于將列表中的元素進行排序。默認按升序排列。
也可以向 sort() 方法傳遞參數(shù) reverse = True 反向排序。
num = [22,11,45,520,987,8] num.sort() print(num) num.sort(reverse=True) print(num)
輸出
[8, 11, 22, 45, 520, 987] [987, 520, 45, 22, 11, 8]
2、對列表進行臨時排序:使用方法 sorted()
要保留列表元素原來的排列順序,同時以特定的順序呈現(xiàn)它們,它使用函數(shù) sorted()。
該函數(shù)能夠按特定順序顯示列表元素,同時不影響它們在列表中的原始排列排序。
cars = ['bmw','audi','toyota','subaru']
print('Here is the original list:',cars)
print('Here is the sorted list:',sorted(cars))
Here is the original list: ['bmw', 'audi', 'toyota', 'subaru'] Here is the sorted list: ['audi', 'bmw', 'subaru', 'toyota']
網(wǎng)站題目:創(chuàng)新互聯(lián)Python教程:python對列表進行永久性或臨時排序的方法
URL標題:http://www.5511xx.com/article/cdoghso.html


咨詢
建站咨詢
