query on python list

Larry Bates larry.bates at websafe.com
Fri Dec 30 10:40:40 EST 2005


I'm having trouble determining what you want but
I think there are a couple of problems in your
code:

list2 = ['1','2','5',4]

did you mean

list2 = ['1','2','3','4']

Note missing quotes around the 4 and
5 instead of 3

If you want to know if list2 is found in list 1
it is as simple as:

if list2 in list1:
    #
    # Do something here
    #

if you want to know if any member of list2 is
found in any list in list 1 then you can just do:

Found=max([y in x for y in list2 for x in list1])

works and you should have some fun picking this one-liner apart
<grin>.

-Larry Bates

Mike Meyer wrote:
> muttu2244 at yahoo.com writes:
> 
>>hi tim
>>thanks for the help
>>acutally i dint tell u the whole problem
>>i have list of lists, for ex
>>
>>list1 =[ ['a','b','c','d','e'] , ['1','2','3','4'] ,  ['A','B','C','D']
>>]
>>
>>and another list
>>
>>list2 = ['1','2','5',4]
>>
>>now am searching the items of list2 in list1 as below
>>
>>Found = True
>>for i in list1:
>>    for j in i:
>>        if not list2[1] == j or not list2[2] == j:
>>                if not list2[0] == j:
>>                    Found = False
>>                elif list2[0] == j:
>>                    Found = True
>>                    break
>>
>>now though it finds the the key in between and sets the "Found=True",
>>but later in the next list of if one item doesnt match it sets again
>>Found = False
>>
>>i hope am clear this time
> 
> 
> You have half the solution. Basically, you should set Found to one
> state, and then only set it againn if it changes. For instance:
> 
> Found = True
> for i in list1:
>     for j in i:
>         if not list2[1] == j or not list2[2] == j:
>            if not list2[0] == j:
>               Found = False
> 
> This will exit the outer loop with Found being False if and only if
> the nested if's in your inner loop set it to False; you never need to
> set it to True. Alternatively, set the initial state to False, and
> only set it to True if you find something.
> 
> For efficiency, you can break from the inner loop, and then check
> found after the inner loop and break a second time if it's changed.
> 
> BTW, the nested ifs in your inner loop don't do what your description
> says they should.
> 
>            <mike
> 
> 
> Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
> Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list