list problem

Simon Forman rogue_pedro at yahoo.com
Wed Jul 26 00:55:05 EDT 2006


placid wrote:
> Simon Forman wrote:
> > 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
> >
> > Well first off, don't use 'str' for a variable name.
> >
> > Second, "%04i" % i creates a string, don't call str() on it.
> >
> > Third, str(1) will always be "1" so just add that to your format string
> > already "1%04i" % i
> >
>
> thanks for the tips
>
> > (And if the "XXX" part is also constant then add that too: "XXX1%04i" %
> > i)
> >
> > Finally, you can say:
> >
> > for i in xrange(1,10):
> >     s = "XXX1%04i" % i
> >     if s not in list1 and s not in list2:
> >         print s
> >
>
> But there may be other characters before XXX (which XXX is constant). A
> better example would be, that string s is like a file name and the
> characters before it are the absolute path, where the strings in the
> first list can have a different absolute path then the second list
> entries. But the filenames are always exact. So you need to split the
> entries bases on "\\" (windows machine) and match on this ?
>
>
> Cheers

hmm, a slightly different problem than your OP.

Yeah, I would build a new list (or set) from the contents of BOTH lists
with the prefixes stripped off and test your target string against
that.  You might also be able to do something with the endswith()
method of strings.

test = set(n[3:] for n in list1) + set(n[3:] for n in list2)

if s not in test: print s


It's late though, so I may be being stupid.  ;-)

Peace,
~Simon




More information about the Python-list mailing list