小编NDT*_*DTB的帖子

Python:如何基于特定元素拆分列表

如果我们在Python中有以下列表

sentence = ["I", "am", "good", ".", "I", "like", "you", ".", "we", "are", "not", "friends", "."]
Run Code Online (Sandbox Code Playgroud)

如何将其拆分以获得包含以句点结束的元素的列表?所以我想在我的新列表中获得以下元素:

["I","am","good","."]
["I","like","you","."]
["we","are","not","friends","."]
Run Code Online (Sandbox Code Playgroud)

到目前为止我的尝试:

cleaned_sentence = []
a = 0
while a < len(sentence):
    current_word = sentence[a]
    if current_word == "." and len(cleaned_sentence) == 0:
        cleaned_sentence.append(sentence[0:sentence.index(".")+1])
        a += 1
    elif current_word == "." and len(cleaned_sentence) > 0:
        sub_list = sentence[sentence.index(".")+1:-1]
        sub_list.append(sentence[-1])
        cleaned_sentence.append(sub_list[0:sentence.index(".")+1])
        a += 1
    else:
        a += 1

for each in cleaned_sentence:
    print(each)
Run Code Online (Sandbox Code Playgroud)

运行此sentence生成

['I', 'am', 'good', '.']
['I', 'like', …
Run Code Online (Sandbox Code Playgroud)

python indexing list

-1
推荐指数
1
解决办法
611
查看次数

标签 统计

indexing ×1

list ×1

python ×1