新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Pythonsort()
python 中的sort()函數(shù)有助于按照用戶定義的順序(升序或降序)對列表進行排序。默認情況下,排序按升序進行。

成都創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務,包含不限于成都網(wǎng)站設計、成都網(wǎng)站建設、外貿(mào)網(wǎng)站建設、資興網(wǎng)絡推廣、微信小程序、資興網(wǎng)絡營銷、資興企業(yè)策劃、資興品牌公關、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務,您的肯定,是我們最大的嘉獎;成都創(chuàng)新互聯(lián)為所有大學生創(chuàng)業(yè)者提供資興建站搭建服務,24小時服務熱線:028-86922220,官方網(wǎng)址:www.cdcxhl.com
**list.sort(key=..., reverse=...)** #where key is function name
排序()參數(shù):
這個函數(shù)有兩個可選參數(shù)。我們也可以使用排序(列表,鍵=...,反向=...)方法出于同樣的目的。不同的是sorted()方法不改變列表并返回一個排序列表,但是sorted()方法直接改變列表并且不返回任何值。
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 反面的 | 如果為真,則排序列表反轉(zhuǎn)(或按降序) | 可選擇的 |
| 鍵 | 用作排序比較的關鍵字的函數(shù) | 可選擇的 |
排序()返回值
sort()方法不返回值。它通過更改元素的順序來更新原始列表。為了返回排序列表而不改變原始列表,我們可以使用sorted()方法。
Python 中sort()方法的示例
示例 1:如何在 Python 中對列表進行排序?
# alphabets list
alphabets = ['b', 'a', 'e', 'd', 'c']
# sort the alphabets
alphabets.sort()
# print alphabets
print('Sorted list:', alphabets)
輸出:
Sorted list: ['a', 'b', 'c', 'd', 'e']
例 2:如何對列表進行降序排序?
# alphabets list
alphabets = ['b', 'a', 'e', 'd', 'c']
# sort the alphabets
alphabets.sort(reverse=True)
# print alphabets
print('Sorted list in Descending order:', alphabets)
輸出:
Sorted list in Descending order: ['e', 'd', 'c', 'b', 'a']
示例 3:如何使用鍵對列表進行排序?
# take second element for sort
def second(elem):
return elem[1]
# random list
randomlist = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
randomlist.sort(key=second)
# print list
print('Sorted list:', randomlist)
輸出:
Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)] 分享標題:創(chuàng)新互聯(lián)Python教程:Pythonsort()
鏈接地址:http://fisionsoft.com.cn/article/cophipi.html


咨詢
建站咨詢
