Pythonsorted ()関数
例
タプルを並べ替えます:
a = ("b", "g", "a", "d", "f", "c", "h", "e")
x = sorted(a)
print(x)
定義と使用法
このsorted()
関数は、指定された反復可能オブジェクトのソートされたリストを返します。
昇順または降順を指定できます。文字列はアルファベット順に並べ替えられ、数字は数字で並べ替えられます。
注:文字列値と数値の両方を含むリストをソートすることはできません。
構文
sorted(iterable, key=key, reverse=reverse)
パラメータ値
Parameter | Description |
---|---|
iterable | Required. The sequence to sort, list, dictionary, tuple etc. |
key | Optional. A Function to execute to decide the order. Default is None |
reverse | Optional. A Boolean. False will sort ascending, True will sort descending. Default is False |
その他の例
例
数値の並べ替え:
a = (1,
11, 2)
x = sorted(a)
print(x)
例
ソート昇順:
a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a)
print(x)
例
降順で並べ替えます。
a = ("h", "b", "a", "c", "f", "d", "e", "g")
x = sorted(a,
reverse=True)
print(x)