[Tutor] Tweaking list comprehensions
Jacob S.
keridee at jayco.net
Mon Feb 14 03:11:48 CET 2005
> Hello,
>
> I am fine tuning list comprehensions (at least my understandng
> thereof), and I'm not near a Python interpreter at the moment, so I
> was wondering if someone could tell me if I did OK -
>
> def approachA(files):
>
> isHTML = []
> for filename in files:
> if filename.endswith('.htm') or filename.endswith('.html'):
> isHTML.append(filename)
> return isHTML
>
> def approachB(files):
>
> isHTML = [filename if filename.endswith('.htm') or\
> filename.endswith(.html') for filename in files]
> return isHTML
No, it should be...
isHTML = [filename for filename in files if filename.endswith('.htm') or\
filename.endswith('.html') for filename in files]
HTH,
Jacob
> I wanted approachB to be the list comprehension verstion of approachA.
> Did I get the syntax right? All seems somewhat back to front to me,
> although when read the comprehension does sorta make sense in a
> twisted way.
>
> Feels almost.. Perlesque in it's perverse compactness. That said,
> saving myself from the cascading sequential conditionals/loops of
> approach A is good, I feel. When it's 2am in the morning, and I've run
> out of coffee, 90% of my bugs have been due to the 'cascades' and one
> misplaced tab.
>
> Regards,
>
>
> Liam Clarke
>
>
>
>
>
> --
> 'There is only one basic human right, and that is to do as you damn well
> please.
> And with it comes the only basic human duty, to take the consequences.
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list