[Tutor] iterating in the same line

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Aug 13 22:35:11 CEST 2005



On Sat, 13 Aug 2005, Jonas Melian wrote:

> I would check 3 words at the starting of a line
>
> s=['foo','bar','qwe']
>
> if ln.startswith(s):   (this is bad)


Hi Jonas,

Just checking: is this similar to a question brought up a few days ago?

    http://mail.python.org/pipermail/tutor/2005-August/040592.html


Do you really need to do this in one line, or would it be sufficient to
write a function definition that you can reuse?  You mentioned earlier
that:

> if ln.startswith(s):   (this is bad)

But the general idea is a good one!  You can write your own function
called startswithany(), which will then read as:

    if startswithany(ln, s): ...

and writing a simple version of startswithany() should be straightforward.



> what is the best way for making it?
>
> if max(map(ln.startswith,s)):
> or
> reduce(lambda m,n:m or n, map(ln.startswith, s))

I'm not so sure about this.  It does more work than it needs to, and it
doesn't scan well for human beings.  *grin*

If you really want to do it this way, at leeast wrap the it in a
well-named function.  But if you really insist on getting it done in one
line, take a look at the Regular Expression HOWTO:

    http://www.amk.ca/python/howto/regex/


Good luck to you!



More information about the Tutor mailing list