Python 的 sorted(~)
方法從可迭代項中返回一個排序列表。
注意
sorted(~)
方法使原始可迭代保持不變。
參數
1. iterable
| iterable
返回排序列表的可迭代對象。
2. reverse
| Boolean
| optional
如果 True
,則排序列表被反轉(按降序排序)。默認為False
(升序)。
3. key
| function
| optional
指定排序標準的函數。該函數應采用單個參數並返回用於排序的鍵。
返回值
從可迭代項中返回一個新的排序列表。
例子
基本用法
要按字母升序返回列表animals
:
animals = ['cat', 'doge', 'bird']
sorted(animals)
['bird', 'cat', 'doge']
反向參數
要按字母降序返回列表animals
:
animals = ['cat','doge','bird']
sorted(animals, reverse=True)
['doge', 'cat', 'bird']
關鍵參數
根據每個元素除以 3 時的餘數對列表 numbers
進行排序:
# A function that returns the remainder when dividing each element by 3
def modulo_3(elem):
return(elem % 3)
numbers = [5, 3, 4, 2]
# Sort numbers list using modulo_3 function as sorting key
sorted(numbers, key=modulo_3)
[3, 4, 5, 2]
請注意,列表現在根據每個元素除以 3 時的餘數按升序排序。
相關用法
- Python sorted()用法及代碼示例
- Python sorted()和sort()用法及代碼示例
- Python NumPy sort方法用法及代碼示例
- Python sort()用法及代碼示例
- Python socket.create_server用法及代碼示例
- Python socket.socket.sendmsg用法及代碼示例
- Python socket.socket.recvmsg_into用法及代碼示例
- Python socket.socket.recvmsg用法及代碼示例
- Python socket.getaddrinfo用法及代碼示例
- Python sklearn.cluster.MiniBatchKMeans用法及代碼示例
- Python NumPy squeeze方法用法及代碼示例
- Python scipy.ndimage.binary_opening用法及代碼示例
- Python scipy.signal.windows.tukey用法及代碼示例
- Python scipy.stats.mood用法及代碼示例
- Python str.isidentifier用法及代碼示例
- Python sklearn.metrics.fbeta_score用法及代碼示例
- Python scipy.fft.ihfftn用法及代碼示例
- Python scipy.stats.normaltest用法及代碼示例
- Python scipy.ndimage.convolve1d用法及代碼示例
- Python scipy.stats.arcsine用法及代碼示例
- Python scipy.interpolate.UnivariateSpline.antiderivative用法及代碼示例
- Python NumPy sign方法用法及代碼示例
- Python scipy.linalg.hadamard用法及代碼示例
- Python sklearn.linear_model.PassiveAggressiveRegressor用法及代碼示例
- Python skimage.feature.graycomatrix用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Python | sorted method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。