Pythonでタプルのリストをn番目の項目で並べ替える
この投稿では、Pythonでタプルのリストをn番目の項目で並べ替える方法について説明します。
1.使用する list.sort()
関数
のPythonicソリューション 所定の位置に タプルのリストを並べ替えるには、 list.sort()
関数。2つのキーワードのみの引数を受け入れることができます。 鍵 と 逆行する。次の例は、いくつかの項目を逆の順序でソートしてタプルのリストをソートする方法を示しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
if __name__ == '__main__': emp = [('John', 'Telecom', 100000), ('Bob', 'IT', 80000), ('John', 'Finance', 70000)] #1.最初の項目で並べ替える emp.sort(key=lambda x: x[0]) # [('Bob', 'IT', 80000), ('John', 'Telecom', 100000), ('John', 'Finance', 70000)] print(emp) # 2.最初の項目で並べ替え、次に2番目の項目で並べ替えます emp.sort(key=lambda x: (x[0], x[1])) # [('Bob', 'IT', 80000), ('John', 'Finance', 70000), ('John', 'Telecom', 100000)] print(emp) #3.1番目と2番目のアイテムを逆の順序で並べ替えます emp.sort(key=lambda x: (x[0], x[1]), reverse=True) # [('John', 'Telecom', 100000), ('John', 'Finance', 70000), ('Bob', 'IT', 80000)] print(emp) # 4.最初の項目で並べ替え、次に3番目の項目(整数)を逆の順序で並べ替えます emp.sort(key=lambda x: (x[0], -x[2])) # [('Bob', 'IT', 80000), ('John', 'Telecom', 100000), ('John', 'Finance', 70000)] print(emp) |
逆の順序で並べ替えられた特定のアイテムが必要ない場合は、 operator.attrgetter()
関数。これはかなり高速に実行されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
from operator import itemgetter if __name__ == '__main__': emp = [('John', 'Telecom', 100000), ('Bob', 'IT', 80000), ('John', 'Finance', 70000)] #1.最初の項目で並べ替える emp.sort(key=itemgetter(0)) # [('Bob', 'IT', 80000), ('John', 'Telecom', 100000), ('John', 'Finance', 70000)] print(emp) # 2.最初の項目で並べ替え、次に3番目の項目で並べ替えます emp.sort(key=itemgetter(0, 2)) # [('Bob', 'IT', 80000), ('John', 'Finance', 70000), ('John', 'Telecom', 100000)] print(emp) # 3.最初のアイテム、次に3番目のアイテムの順に並べ替えます。 emp.sort(key=itemgetter(0, 2), reverse=True) # [('John', 'Telecom', 100000), ('John', 'Finance', 70000), ('Bob', 'IT', 80000)] print(emp) |
2.使用する sorted()
関数
新しいソート済みリストを取得するには、 sorted()
ビルトイン。と同じ引数を受け入れます sort()
関数。これを以下に示します。
1 2 3 4 5 6 7 8 9 10 |
if __name__ == '__main__': emp = [('John', 'Telecom', 100000), ('Bob', 'IT', 80000), ('John', 'Finance', 70000)] #は最初の項目でソートし、次に2番目の項目でソートします sortedList = sorted(emp, key=lambda x: (x[0], x[1])) # [('Bob', 'IT', 80000), ('John', 'Finance', 70000), ('John', 'Telecom', 100000)] print(sortedList) |
これで、Pythonでタプルのリストをn番目の項目で分別ることができます。