从一个字符串列表开始,如果您想拆分这些字符串,有两种方法可以这样做,具体取决于您想要的输出是什么。
情况1:一个字符串列表(old_list)拆分为一个新的字符串列表(new_list)。
例如['This is a Sentence', 'Also a sentence']->;['This', 'is', 'a', 'Sentence', 'Also', 'a', 'sentence']。
步骤:把绳子绕起来。for sentence in old_list:
创建新字符串以跟踪当前单词(word)。
循环遍历每个字符串中的字符。for ch in sentence:
如果遇到要拆分的字符(本例中为空格),请检查word是否为空并将其添加到新列表中,否则将该字符添加到word。
确保在遍历所有字符后将word添加到列表中。
最终代码:new_list = []
for sentence in old_list:
word = ''
for ch in sentence:
if ch == ' ' and word != '':
new_list.append(word)
word = ''
else:
word += ch
if word != '':
new_list.append(word)
这相当于new_list = []
for sentence in old_list:
new_list.extend(sentence.split(' '))
或者更简单new_list = ' '.join(old_list).split(' ')
情况2:一个字符串列表(old_list)拆分为一个新的字符串列表(new_list)。
例如['This is a Sentence', 'Also a sentence']->;[['This', 'is', 'a', 'Sentence'], ['Also', 'a', 'sentence']]。
步骤:把绳子绕起来。for sentence in old_list:
创建一个新字符串来跟踪当前单词(word)和一个新列表来跟踪此字符串中的单词(sentence_list)。
循环遍历每个字符串中的字符。for ch in sentence:
如果遇到要拆分的字符(本例中为空格),请检查word是否为空并将其添加到sentence_list,否则将该字符添加到word。
确保在遍历所有字符后将word添加到sentence_list。
Append(不是extend)sentence_list到新列表并移到下一个字符串。
最终代码:new_list = []
for sentence in old_list:
sentence_list = []
word = ''
for ch in sentence:
if ch == ' ' and word != '':
sentence_list.append(word)
word = ''
else:
word += ch
if word != '':
sentence_list.append(word)
new_list.append(sentence_list)
这相当于new_list = []
for sentence in old_list:
new_list.append(sentence.split(' '))
或使用列表理解new_list = [sentence.split(' ') for sentence in old_list]