"Find" in list of objects

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?ISO-8859-1?Q?Andreas_M=FCller?=

    "Find" in list of objects

    Hi!

    (Python 2.2.3 if this is relevant :-)

    I have a list of objects with, lets say, the attributes "ID", "x" and
    "y". Now I want to find the index of list element with ID=10.

    Of course I can loop through the list manually, but is there a
    construct like

    list.find (10, key='ID')

    ? Thanks for your ideas.

    Best regards,
    Martin



  • bearophileHUGS@lycos.com

    #2
    Re: "Find&quot ; in list of objects

    Andreas Müller:
    is there a construct like
    list.find (10, key='ID')
    You can create yourself a little convenience function, or you can use
    something like the following. First some testing code:

    class C:
    def __init__(self, id):
    self.id = id
    def __repr__(self):
    return "<%s>" % self.id
    seq = map(C, [1, -5, 10, 3])
    print seq

    That prints:
    [<1>, <-5>, <10>, <3>]

    Then you can find the index of all the classes with id = 10:
    print [i for i, obj in enumerate(seq) if obj.id == 10]

    It returns a [2]. If seq doesn't contain the requires object(s) it
    returns an empty list.

    Or just the first, working lazily:
    print (i for i, obj in enumerate(seq) if obj.id == 10).next()

    This time if seq doesn't contain the requires object(s) it raises a
    StopIteration exception.

    You can of course wrap that into a function, using seq and 10 as
    arguments.

    Bye,
    bearophile

    Comment

    • Gabriel Genellina

      #3
      Re: &quot;Find&quot ; in list of objects

      En Thu, 23 Oct 2008 05:23:51 -0200, Andreas Müller <hufflehuffle@w est.de>
      escribió:
      (Python 2.2.3 if this is relevant :-)
      >
      I have a list of objects with, lets say, the attributes "ID", "x" and
      "y". Now I want to find the index of list element with ID=10.
      >
      Of course I can loop through the list manually, but is there a
      construct like
      >
      list.find (10, key='ID')
      If you define __eq__ for your objects you may use list.index:

      class Obj:
      def __init__(self, id_, x=0, y=0):
      self.id = id_
      self.x = x
      self.y = y
      def __eq__(self, other):
      if not isinstance(othe r, Obj): raise NotImplementedE rror
      return self.id==other. id

      pya = Obj(10)
      pyb = Obj(11)
      pyc = Obj(12)
      pyalist = [a,b,c]
      pyprint alist.index(Obj (11))
      1
      pyprint alist.index(Obj (20))
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      ValueError: list.index(x): x not in list

      Note that this is a "global" change - two separate instances with the same
      ID were "not equal" before, and are "equal" now, everywhere, not just
      regarding list.index

      Of course you always have the old "for" loop solution (`enumerate` would
      make things a lot nicer, but it requires 2.3):

      def index_by_id(ali st, id_):
      for i in range(len(alist )):
      if alist[i].id==id_:
      return i

      --
      Gabriel Genellina

      Comment

      • bearophileHUGS@lycos.com

        #4
        Re: &quot;Find&quot ; in list of objects

        Andreas Müller:
        is there a construct like
        list.find (10, key='ID')
        Given the current Python a syntax like this is more probable:

        somelist.find(1 0, key=attrgetter( 'ID'))

        Bye,
        bearophile

        Comment

        Working...