从字符串列表中提取每个单词

2024-09-28 21:20:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用Python 我的名单是

str = ["Hello dude", "What is your name", "My name is Chetan"]

我想将字符串中每个句子中的每个单词分开,并将其存储在新的\u列表中。新列表如下

new_list = ["Hello", "dude", "What", "is", "your", "name", "My", "name", 
            "is", "Chetan"]

我试过密码

for row in str:
    new_list.append(row.split(" "))

输出:

[['Hello', 'dude'], ['What', 'is', 'your', 'name'], ['My', 'name', 'is', 
  'Chetan']]

哪一个是列表的列表


Tags: 字符串namehello列表newyourismy
3条回答

你可以用^{}

from itertools import chain

def split_list_of_words(list_):
    return list(chain.from_iterable(map(str.split, list_)))

演示

input_ = [
          "Hello dude", 
          "What is your name", 
          "My name is Chetan"
         ]

result = split_list_of_words(input_)

print(result)
#['Hello', 'dude', 'What', 'is', 'your', 'name', 'My', 'name', 'is', 'Chetan']

这应该会有帮助。使用extend+=代替append

str = ["Hello dude", "What is your name", "My name is Chetan"]
new_list = []
for row in str:
    new_list += row.split(" ") #or new_list.extend(row.split(" "))

print new_list

输出

['Hello', 'dude', 'What', 'is', 'your', 'name', 'My', 'name', 'is', 'Chetan']
new_list = [x for y in str for x in y.split(" ")]

相关问题 更多 >