Python中的逗号分隔和空格分隔

2024-04-25 06:39:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些python代码,可以用逗号分隔,但是没有去掉空白:

>>> string = "blah, lots  ,  of ,  spaces, here "
>>> mylist = string.split(',')
>>> print mylist
['blah', ' lots  ', '  of ', '  spaces', ' here ']

我宁愿这样删除空白:

['blah', 'lots', 'of', 'spaces', 'here']

我知道我可以循环遍历list和strip()每个项,但是,由于这是Python,我猜有一种更快、更简单、更优雅的方法来完成它。


Tags: of方法代码stringhere空白listspaces
3条回答

使用列表理解——更简单,就像for循环一样容易阅读。

my_string = "blah, lots  ,  of ,  spaces, here "
result = [x.strip() for x in my_string.split(',')]
# result is ["blah", "lots", "of", "spaces", "here"]

参见:Python docs on List Comprehension
A good 2 second explanation of list comprehension.

使用正则表达式拆分。注:我用前导空格使情况更一般。列表理解是删除前面和后面的空字符串。

>>> import re
>>> string = "  blah, lots  ,  of ,  spaces, here "
>>> pattern = re.compile("^\s+|\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['blah', 'lots', 'of', 'spaces', 'here']

即使^\s+不匹配,此操作仍然有效:

>>> string = "foo,   bar  "
>>> print([x for x in pattern.split(string) if x])
['foo', 'bar']
>>>

这就是为什么您需要^\s+:

>>> pattern = re.compile("\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['  blah', 'lots', 'of', 'spaces', 'here']

看到布拉赫的领先位置了吗?

说明:上面使用了Python3解释器,但Python2的结果是相同的。

我来补充:

map(str.strip, string.split(','))

但看到杰森·奥伦多夫在a comment中已经提到过。

读到格伦·梅纳德在同一个答案中的评论,我开始想为什么。我以为他是出于表演的原因,但当然他可能是出于文体的原因,或者其他什么原因(格伦?)。

那么快(可能有缺陷?)在我的盒子上应用三种方法的循环测试显示:

[word.strip() for word in string.split(',')]
$ time ./list_comprehension.py 
real    0m22.876s

map(lambda s: s.strip(), string.split(','))
$ time ./map_with_lambda.py 
real    0m25.736s

map(str.strip, string.split(','))
$ time ./map_with_str.strip.py 
real    0m19.428s

使map(str.strip, string.split(','))成为赢家,尽管看起来他们都在同一个圈子里。

当然,由于性能方面的原因,不一定排除map(带lambda或不带lambda),对我来说,它至少和列表理解一样清楚。

编辑:

Ubuntu 10.04上的Python 2.6.5

相关问题 更多 >