1. ホーム
  2. python

[解決済み] Python のリストの降順でのソート

2022-03-23 05:41:15

質問

このリストを降順に並べ替えるにはどうしたらよいですか?

timestamps = [
    "2010-04-20 10:07:30",
    "2010-04-20 10:07:38",
    "2010-04-20 10:07:52",
    "2010-04-20 10:08:22",
    "2010-04-20 10:08:22",
    "2010-04-20 10:09:46",
    "2010-04-20 10:10:37",
    "2010-04-20 10:10:58",
    "2010-04-20 10:11:50",
    "2010-04-20 10:12:13",
    "2010-04-20 10:12:13",
    "2010-04-20 10:25:38"
]

解決方法は?

一行で lambda :

timestamps.sort(key=lambda x: time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6], reverse=True)


に関数を渡す list.sort :

def foo(x):
    return time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6]

timestamps.sort(key=foo, reverse=True)