有什么方法可以简化此功能?具体来说,我想用更少的缩进行来重写它。
# split string (first argument) at location of separators (second argument, should be a string)
def split_string(text, separators):
text = ' ' + text + ' '
words = []
word = ""
for char in text:
if char not in separators:
word += char
else:
if word:
words.append(word)
word = ""
if not words:
words.append(text)
return words
最佳答案
您的代码似乎产生了
>>> split_string("foo.,.bar", ".,")
[' foo']
但是你的评论说
split_string("foo.,.bar", ".,") will return ["foo", "bar"]
假设注释是预期的,那么我将使用
itertools.groupby
(我讨厌使用正则表达式):from itertools import groupby
def splitter(text, separators):
grouped = groupby(text, lambda c: c in separators)
return [''.join(g) for k,g in grouped if not k]
这使
>>> splitter("foo.,.bar", ".,")
['foo', 'bar']
groupby
返回按术语的某些功能(在本例中为lambda c: c in separators
)分组的连续术语上的迭代器。关于python - 如何简化此功能?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16224585/