我正在尝试将一系列包含句子的字符串转换为列表,例如:
将其转换为以下内容:
我尝试使用这个:
我以为它会将每个字符串取出,并将该字符串的每个项目追加到word_list中,但实际输出的结果大致是这样的:
sentence = ['Here is an example of what I am working with', 'But I need to change the format', 'to something more useable']
将其转换为以下内容:
word_list = ['Here', 'is', 'an', 'example', 'of', 'what', 'I', 'am',
'working', 'with', 'But', 'I', 'need', 'to', 'change', 'the format',
'to', 'something', 'more', 'useable']
我尝试使用这个:
for item in sentence:
for word in item:
word_list.append(word)
我以为它会将每个字符串取出,并将该字符串的每个项目追加到word_list中,但实际输出的结果大致是这样的:
word_list = ['H', 'e', 'r', 'e', ' ', 'i', 's' .....etc]
我知道我在犯一个愚蠢的错误,但我想不出为什么,有人可以帮忙吗?
[word for line in sentence for word in line.split()]
。 - Andrew Clark[line for line in sentence]
,但我不理解第二部分for word in line.split()
。它与[line.split() for line in sentence]
有什么不同? - addicted