[Tutor] Alternative to nested loops
Steve Nelson
sanelson at gmail.com
Sun Mar 19 23:58:49 CET 2006
On 3/19/06, John Fouhy <john at fouhy.net> wrote:
> What you're doing is called "flattening" a list. You can do it with a
> list comprehension:
>
> >>> foo = [[1,2,3], [4,5,6], [7,8,9]]
> >>> [x for y in foo for x in y]
> [1, 2, 3, 4, 5, 6, 7, 8, 9]
Ah yes, that was the sort of thing I was thinking of.
> If you want to sum, you could also use a generator expression
> (requires Python 2.4):
I am on 2.3.5 so I can do sum([x for y in foo for x in y])
So now looking at both your and Karl's ways, how do I catch
exceptions. My current (working) code looks like this:
def fleetHealth(self):
"""Iterate through each square to see if the whole fleet has been sunk."""
s = 0
for c in self.ranks:
for b in c:
try:
s += b.contents.size()
except:
pass
return s
I guess this could be significantly refactored! But... readability counts!
S.
More information about the Tutor
mailing list