Can this python code be expressed with list comprehension? -
i find following readable, wondering if more pythonesque manner accomplish (perhaps list comprehension)?
import re cgi_keys = [ '_none___total', '_george___total', 'greg__total', '_geoff___total', '_gillian_total' ] pattern = re.compile(r"_(.+)___(.+)") totals = [] key in cgi_keys: m = pattern.match(key) if m: totals.append(m.groups()) totals which display:
[('none', 'total'), ('george', 'total'), ('geoff', 'total')] but hoping figure out way above using construct such as:
[key key in cgi_keys if pattern.match(key)] displaying strings in less useful form:
['_none___total', '_george___total', '_geoff___total'] is worth trying achieve breaking filtered strings tuples, or lists list comprehension?
actually use:
totals = (pattern.match(key) key in cgi_keys) totals = [match.groups() match in totals if match] which shorter still efficient because first affectation generator values won't evaluated until second statement.
also, use:
totals = [match.groups match in filter(none, map(pattern.match, cgi_keys))] as map() gives generator. you'd have use imap in python 2 instead. same goes ifilter.
note if cgi_keys small, may use map in python 2 extra-work done iterating twice unnoticeable anyway.
Comments
Post a Comment