Multiple splits on a single line in Python
I would like to know if there is a more compact (or Pythonic) way of doing several splits of some input string.开发者_如何学Python Now I'm doing:
[a,bc,de] = 'a,b:c,d/e'.split(',')
[b,c] = bc.split(':')
[d,e] = de.split('/')
I'd use the regular expression library. You don't need to use lists for unpacking, you can use tuples as below.
import re
regex = re.compile(r'[,:/]')
a, b, c, d, e = regex.split('a,b:c,d/e')
You're better of with regex split method probably. Don't do this, it will be crazy slow, but just to add the answer:
a,b,c,d,e = flatten( (x.split(',') for x in y.split(':')) for y in z.split('/') )
(flatten left as an exercise for the reader (see flatten))
精彩评论