LoginSignup
0
0

More than 1 year has passed since last update.

[py2rb] sorted key=itemgetter

Posted at

はじめに

移植やってます。
( from python 3.7 to ruby 2.7 )

sorted (Python)

import operator as op
import string
from itertools import count

psms = list(zip(count(), string.ascii_uppercase + string.ascii_lowercase,
            np.arange(0.01, 0.062, 0.001)))
key = op.itemgetter(0)  # 関数を設定
ipsms = iter(psms)
spsms = sorted(ipsms, key=key)  # 今回はここの話

sortedのオプションkeyに関数を指定することにより、その戻り値によってソートすることができます。

分かりやすい記事はこちら

ただし、今回のソート対象の場合、key = lambda x: x[0]でも行けそうな気もしますし、途中のiter()が無くても動作します。

どうすRuby

まずは、小手調べで絶対値の昇順でソートする例。

l_2d = [[2, 10], [1, -30], [-3, 20]]

p l_2d.sort_by{ |x| x.map{ |y| y.abs }.max }

# [[2, 10], [-3, 20], [1, -30]]

ふむふむ。

l_2d = [[2, 10], [1, -30], [-3, 20]]

key = lambda { |x| x.map{ |y| y.abs }.max }
p l_2d.sort_by{ |x| key.call(x) }

# [[2, 10], [-3, 20], [1, -30]]

これで、lambdaによりソート方法を後から変更することが可能に。

メモ

  • Python の sorted を学習した
  • 百里を行く者は九十里を半ばとす
0
0
2

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
0
0