gpt4 book ai didi

python - 如何通过特定的字符串元素将字符串列表拆分为字符串子列表

转载 作者:IT老高 更新时间:2023-10-28 20:31:41 26 4
gpt4 key购买 nike

我有一个如下的单词列表。我想按 . 拆分列表。 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']]

最佳答案

使用 itertools.groupby

from itertools import groupby
a = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.']
result = [list(g) for k,g in groupby(a,lambda x:x=='.') if not k]
print (result)
#[['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice']]

关于python - 如何通过特定的字符串元素将字符串列表拆分为字符串子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47604449/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com