list problem

zutesmog at gmail.com zutesmog at gmail.com
Wed Jul 26 09:41:56 EDT 2006


placid wrote:
> Hi all,
>
> I have two lists that contain strings in the form string + number for
> example
>
> >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']
>
> the second list contains strings that are identical to the first list,
> so lets say the second list contains the following
>
> >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']
>
> and now what ive been trying to do is find the first string that is
> available,
> i.e a string that is in neither of the two lists so the following code
> should only print XXX4 then return.
>
> for i in xrange(1,10):
>     numpart = str(1) + str("%04i" %i)
>     str = "XXX" + numpart
>
>       for list1_elm in list1:
>           if list1_elm == str:
>                break
>           else:
>                for list2_elm in list2:
>                    if list2_elm == str:
>                       break
>                    else:
>                       print str
>                       return
>
> Cheer

Just a thought

I would probably use sets and see if the value that you are looking for
using the
union of the two lists. (Yes it won't scale to really big lists)
for instance if you do the following
set1 = set(list1)
set2 = set(list2)


you can then do a single check

if "XXX%d" % i not in set1.union(set2):  # or set1 | set2
     # do something

Rgds

Tim




More information about the Python-list mailing list