Skip to content

Instantly share code, notes, and snippets.

@23maverick23
Created February 11, 2017 15:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 23maverick23/28dd50429855bdfb43118178d29dccb9 to your computer and use it in GitHub Desktop.
Save 23maverick23/28dd50429855bdfb43118178d29dccb9 to your computer and use it in GitHub Desktop.
Python: Regexp in list comprehension (shortcut syntax)
# Taken from Stack Overflow answer http://stackoverflow.com/a/2436623/4093021
import re
# items = ['[1] rymoio [rymoio 7s] foo bar', '[2] baz [rymoio 2d] hello world']
# assign matches to callable group parameters
regex = r"(?P<who>.*\[.*\]\s)(?P<what>.*)"
# bound method outside of the listcomp optimization
src = re.search
# assign matches to m within listcomp
items = [[m.group('who'), m.group('what')] for item in items for m in [src(regex, item)] if m]
# >>> [['[1] rymoio [rymoio 7s] ', 'foo bar'], ['[2] baz [rymoio 2d] ', 'hello world']]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment