简体   繁体   English

Python 中单行上的多个拆分

[英]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.我想知道是否有更紧凑(或 Pythonic)的方式来对某些输入字符串进行多次拆分。 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 )) (将左侧展平作为练习供读者使用(请参阅展平))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM