[Python-ideas] More power in list comprehensions with the 'as' keyword
Terry Reedy
tjreedy at udel.edu
Thu Aug 28 22:37:20 CEST 2008
Mathias Panzenböck wrote:
> Marcin 'Qrczak' Kowalczyk schrieb:
>> 2008/8/28 Cesare Di Mauro <cesare.dimauro at a-tono.com>:
>> [stripped | l <- text.split('\n'), let stripped = l.strip(), stripped != '']
>>
>> Python borrowed 2 out of 3 kinds of list comprehension constructs.
>>
>
> so maybe?
>
> [stripped for l in text.split('\n') if stripped != '' let stripped = l.strip()]
To parallel the Haskell-ish example, this should be
[stripped for l in text.split('/n') stripped as l.strip() if stripped != '']
but the clause has 'as' in the middle instead of at the beginning,
making it hard to parse. Haskell used commas
[stripped for l in text.split('/n'), stripped as l.strip(), if stripped
!= '']
but I think this would conflict with Python's other comma usage. Most
feasible, I think, would be
[stripped for l in text.split('/n') with stripped as l.strip() if
stripped != '']
This corresponds to the multi-statement for loop version
_=[]
for l in text.split('\n'):
stripped = l.strip()
if stripped != '':
_.append(stripped)
with 'stripped = l.strip()' replaced by 'with stripped as l.strip()'.
If other use cases were presented that could not be more easily written
otherwise, as with the re.split() version, I might at least be neutral
on this.
Terry Jan Reedy
More information about the Python-ideas
mailing list