Help us understand the problem. What is going on with this article?

Python リストを参照してリストをソート

More than 1 year has passed since last update.

やはり先人の知恵に頼るべき.
もっと楽にやる方法が有るかもしれないがとりあえずメモ.

リスト.sortでもsorted(リスト) でも良いと思うがsortedのほうが元のリストを変更しないのでここではsorted()を用いる

問題

以下のように2つのリストがある時,片方のリストの値を用いてもう片方のリストをソートしたい.

X = ["a", "b", "c", "d", "e", "f"]
Y = [ 0,   5,   3,    1,   4,   2]

Yでソートするなら答えはこうなるべき.
['a', 'd', 'f', 'c', 'e', 'b']

最短解[1]

多分これが一番早そう.

Z = [x for _,x in sorted(zip(Y,X))]
print(Z) 

やっていることは,

  • ZIPで数値と文字列を結合
  • sortedで最初のYの値を見てソート
  • 2番目の要素だけ取り出す

いろいろと参考になる.こういうのが即浮かばないうちはPython使いにはなれんのか.

Reference[2]読んで考えて書いたやつ

自分で考えて書くと可読性が低い.

deco = zip(X,Y)
sorted(deco,key=lambda deco:deco[:][1])

keyの後ろにはXの要素(アルファベット)を与えるとYの値(順序に使う数値)を出すような関数を書けば良い.
従ってzipでXとYをくっつけてY側の値を取り出すという関数にした.

文献

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away