「python入門」sorted()、min()とmax()でリストを並べ替えるサンプル

1.sorted()
>>> l = [{'x’:1, 'y’:2}, {'x’:2, 'y’:3}, {'x’:3, 'y’:4}]
>>> l1 = sorted(l, key=lambda d:d['x’], reverse=True)
>>> l1
[{'y’: 4, 'x’: 3}, {'y’: 3, 'x’: 2}, {'y’: 2, 'x’: 1}]
>>>

2.itemgetter()
>>> from operator import itemgetter
>>> l = [{'x’:1, 'y’:2}, {'x’:2, 'y’:3}, {'x’:3, 'y’:4}]
>>> l2 = sorted(l, key=itemgetter('x’), reverse=True)
>>> l2
[{'y’: 4, 'x’: 3}, {'y’: 3, 'x’: 2}, {'y’: 2, 'x’: 1}]
>>>

3.min()とmax()
>>> min(l, key=itemgetter('x’))
{'y’: 2, 'x’: 1}
>>> max(l, key=itemgetter('x’, 'y’))
{'y’: 4, 'x’: 3}
>>> max(l, key=itemgetter('x’))
{'y’: 4, 'x’: 3}
>>>

Python

Posted by arkgame