Help with searching a list

John Hunter jdhunter at nitace.bsd.uchicago.edu
Tue Nov 12 10:35:34 EST 2002


>>>>> "Tony" == Tony C <cappy2112 at yahoo.com> writes:

    Tony> Python newbie needs help with searching a list of lists.
    Tony> What is the correct way for search a list of lists ?

You can do this by 'flattening' the list -- ie, turning into a single
list with all the elements of the component lists (recursively).  Look
at the flatten recipe in the Python Cookbook or on the Active State
site.  Here is a slightly modified version that takes bits from both.
It required python2.2 because it uses generators

from __future__ import generators

def iterable(obj):
   try: iter(obj)
   except: return 0
   return 1
      
def is_string_like(obj):
   try: obj + ''
   except (TypeError, ValueError): return 0
   return 1

def is_scalar(obj):
   return is_string_like(obj) or not iterable(obj)

def flatten(seq, scalarp=is_scalar):
   """
   this generator flattens nested containers such as

    >>> l=( ('John', 'Hunter'), (1,23), [[[[42,(5,23)]]]])

    so that

    >>> for i in flatten(l): print i,
    John Hunter 1 23 42 5 23

    By: Composite of Holger Krekel and Luther Blissett
    From: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/121294
      and Recipe 1.12 in cookbook
   """
   for item in seq:
      if scalarp(item): yield item
      else:
         for subitem in flatten(item, scalarp):
            yield subitem

l = flatten([ ['hello',5], ['bye',2] ])

if 'bye1' in l: print 'Yep'
else: print 'Nope'

John Hunter



More information about the Python-list mailing list