16
15

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 5 years have passed since last update.

リストの中のインスタンスのもつ値で検索

Last updated at Posted at 2012-12-26

target_listを線形に探索していく場合、以下のコードが効率がよく、柔軟で、さらに簡潔。
next(( {x} for {x} in {target_list} if {condition} ),None)
第2変数は見つからなかった場合に返ってくる値。
nextを使うことで、条件にあるもののうち、もっとも先頭にあるものをとってくることができ、効率がいい。

class Hoge(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y
hoge_list=[Hoge(10,20),Hoge(10,30),Hoge(5,3),...]
found=next( (hoge for hoge in hoge_list if hoge.x==10 and hoge.y==30) ,None)

参考
http://dev.ionous.net/2009/01/python-find-item-in-list.html

16
15
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
16
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?