2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonでtupleのlistを複数キーの昇降順を指定してソートする

Posted at

やりたいこと

SQLでソートするときには

Select * from table Order By key1 DESC, key2 ASC

のように各キーの昇降順を指定することができます。

またC/C++などでは比較関数を自分で定義することで同様のことができます。

int compare(const MyStruct *a, const MyStruct *b)
{
    if(a->k1 == b->k1){
        return b->k2 - a->k2;
    }else{
        return a->k1 - b->k2;
    }
}

一方でPythonではsortはkey関数と全体の昇降順しか指定することしかできず、複数要素を持つtupleをこのようにsortする場合はどうすればいいのか。

解決方法

公式docに書いてありました。
https://docs.python.org/3/howto/sorting.html#sort-stability-and-complex-sorts

Sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.

This wonderful property lets you build complex sorts in a series of sorting steps. For example, to sort the student data by descending grade and then ascending age, do the age sort first and then sort again using grade

def multisort(xs, specs):
    for key, reverse in reversed(specs):
        xs.sort(key=lambda x: x[key], reverse=reverse)
    return xs

Pythonのソートは安定ソートなので優先順位の低いkeyから順に昇降順を指定して繰り返しソートすればいいのです。なるほどね!!

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?