LoginSignup
3
7

More than 5 years have passed since last update.

maxやmin関数を使って一発でリスト内から所望の要素をgetする

Posted at

やりたいこと

あるリストの中から、特定の値が最大(最小)の要素を取得したい

活用例1:
文字列のリストの中から、文字数が最大のもの

活用例2:
あるクラスのメンバ変数の値が最大(最小)のもの

コード例

文字列の最大・最小の要素を特定する

strlist = [ "bcd", "fg", "abcdefg", "xyz" ]
max_len_element = max(strlist, key=len)
min_len_element = min(strlist, key=len)
print(max_len_element) # -> "abcdefg"
print(min_len_element) # -> "fg"

なお、key=lenを指定しない場合、文字列の1文字目のordの最大の要素を返す仕様みたい
(pythonのmaxには特に明記されていないように感じますが、検証したところそうみたいでした)

クラスのメンバ変数の値が最大(最小)の要素を特定する

#!/usr/bin/env python
# -*- coding:utf-8 -*-
class Foo(object):
    """
    Sample class
    """
    def __init__(self, name, age):
        """
        initialize method
        """
        self.name = name
        self.age = age

    def __repr__(self):
        """
        representaion method
        """
        return self.name

foolist = [ Foo("foo1", 10), Foo("foo2", 15), Foo("foo3", 4) ]
max_age_foo = max(foolist, key=lambda x:x.age) # foo2 のインスタンス
min_age_foo = min(foolist, key=lambda x:x.age) # foo1 のインスタンス

print(max(foolist, key=lambda x:x.age)) # -> foo2
print(min(foolist, key=lambda x:x.age)) # -> foo3

sortして一番大きい(小さい)要素を取得するよりも速度も速かったので、
最大(最小)のみを利用するのであれば、maxやminを使うのがよさげ。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import random

from timer import Timer

class Foo(object):
    """
    Sample class
    """
    def __init__(self, name, age):
        """
        initialize method
        """
        self.name = name
        self.age = age

    def __repr__(self):
        """
        representaion method
        """
        return self.name

timer = Timer()

foolist = [ Foo("foo%d" % i, random.randint(0, 1000)) for i in range(1000) ]

timer.start("using max")
max_foo = max(foolist, key=lambda x:x.age)
timer.stop("using max")
print("using max: %.3f" % timer.get_result("using max"))

barlist = [ Foo("foo%d" % i, random.randint(0, 1000)) for i in range(1000) ]
timer.start("using sort")
max_foo = sorted(barlist, key=lambda x:x.age, reverse=True)[0]
timer.stop("using sort")
print("using sort: %.3f" % timer.get_result("using sort"))

出力結果

using max: 0.001
using sort: 0.003

参考

3
7
3

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