【发布时间】:2018-05-16 05:04:58
【问题描述】:
我有一个如下的单词列表。我想按. 拆分列表。 Python 3 中有没有更好或有用的代码?
a = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.']
result = []
tmp = []
for elm in a:
if elm is not '.':
tmp.append(elm)
else:
result.append(tmp)
tmp = []
print(result)
# result: [['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice']]
更新
添加测试用例以正确处理。
a = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.']
b = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.', 'yes']
c = ['.', 'this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.', 'yes']
def split_list(list_data, split_word='.'):
result = []
sub_data = []
for elm in list_data:
if elm is not split_word:
sub_data.append(elm)
else:
if len(sub_data) != 0:
result.append(sub_data)
sub_data = []
if len(sub_data) != 0:
result.append(sub_data)
return result
print(split_list(a)) # [['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice']]
print(split_list(b)) # [['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice'], ['yes']]
print(split_list(c)) # [['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice'], ['yes']]
【问题讨论】:
-
它认为有一个单线解决方案,没有额外的库,可以使用列表理解和字符串函数接近您的速度。
-
@ScottBoston 我认为有一些有用的功能:)。但我很高兴看到许多有趣的答案。
-
您不应该使用
is运算符来比较字符串顺便说一句。 -
看来您已经拆分了一次字符串。如果您的 first 拆分是按句子进行的,那么您的问题会简单得多。
标签: python python-3.x list split