- Goal
2次元配列を複数のKeyでソートしたい
- How
itemgetterを使う。
- Example
入力)
Udon 500 大阪店
Udon 700 東京店
Ramen 1000 大阪店
Ramen 1200 大阪店
Udon 500 福岡店
Apple 100 福岡店
これを、メニュー(ABC順)→値段(高いものから)並べたい。 - Source
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters# -*- coding: utf-8 -*- import sys from operator import itemgetter # input a = [] for i in range(6): a1, a2, a3 = map(str, input().split()) a.append([a1, int(a2), a3]) # ソート前 print('Before Sort') print(a) print('\nSort by Price') a.sort(key=itemgetter(1), reverse=True) print(a) print('\nThen sort by menu') a.sort(key=itemgetter(0)) print(a)
- Result
% python sort_itemgetter.py
Udon 500 大阪店
Udon 700 東京店
Ramen 1000 大阪店
Ramen 1200 大阪店
Udon 500 福岡店
Apple 100 福岡店
Before Sort
[['Udon', 500, '大阪店'], ['Udon', 700, '東京店'], ['Ramen', 1000, '大阪店'], ['Ramen', 1200, '大阪店'], ['Udon', 500, '福岡店'], ['Apple', 100, '福岡店']]
Sort by Price
[['Ramen', 1200, '大阪店'], ['Ramen', 1000, '大阪店'], ['Udon', 700, '東京店'], ['Udon', 500, '大阪店'], ['Udon', 500, '福岡店'], ['Apple', 100, '福岡店']]
Then sort by menu
[['Apple', 100, '福岡店'], ['Ramen', 1200, '大阪店'], ['Ramen', 1000, '大阪店'], ['Udon', 700, '東京店'], ['Udon', 500, '大阪店'], ['Udon', 500, '福岡店']]
Oracle Application Express Notes | Apps development Notes | Google Cloud Platform | Python | apps test | Cool Beans | English | Books
2019/05/27
2次元配列を複数のKeyでソートする --- Python3
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿