newbie question: for loop within for loop confusion
Thomas Hill
tomlikestorock at gmail.com
Mon Jun 16 17:44:11 EDT 2008
On Jun 16, 2:34 pm, Thomas Hill <tomlikestor... at gmail.com> wrote:
> On Jun 15, 6:23 pm, takayuki <lawtonp... at gmail.com> wrote:
>
> > def hasnolet(avoid):
> > fin = open('animals.txt')
> > for line in fin:
> > word = line.strip()
> > for letter in avoid:
> > if letter in word:
> > break
> > else:
> > print word
>
> You're using the split command correctly, but you're not filtering
> correctly. Consider this:
>
> ---begin---
> fin = open('animals.txt')
> "\n".join(["%s" % line for line in fin if len(line.strip('abcd')) ==
> len(line)])
> ----end----
>
> Let's go slow.
>
> "\n".join([...])
>
> 1. Take everything that is in the following list, and print each one
> with a carriage return appended to it.
>
> "\n".join(["%s" % line for line in fin ...])
>
> 2. For each line in fin, create a string that only consists of what
> currently in the line variable, using string substitution.
>
> "\n".join(["%s" % line for line in fin if len(line.strip('abcd')) ==
> len(line)])
>
> 3. Only do #2 if the length of the line after stripping out the
> unnecessary characters is the same length as the line originally. This
> way we filter out the lines we don't want. If we wanted the lines that
> have been filtered, we can change "==" to "!=" or "<=".
>
> Now, I read "Dive Into Python" first, which through these early on in
> the book. If your eyes cross looking at this, write it down and read
> it again after you get a little farther into the book you're reading
Guh, no, I'm reading the description of strip wrong. Fooey. Anyone
else able to one line it?
More information about the Python-list
mailing list