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

4
我正在使用Python编程语言,我的列表如下:
str = ["Hello dude", "What is your name", "My name is Chetan"]

我希望您能将字符串中每个句子中的单词分开并存储到新列表 new_list 中。new_list 将会是这样的:
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']]

这是一个列表的列表


3
请勿使用 str 作为变量名,因为这会掩盖内置的 str - Ryan Haining
这让我很感兴趣,因为它是少数在Haskell中比Python更简洁的代码之一。concatMap words originalList - Adam Smith
split() 而不是 split(' ') 可以处理多个连续空格字符的情况。 - Ryan Haining
7个回答

3
您可以使用 itertools.chain
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']

2

你有以下内容:

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

然后使用这个一行代码

' '.join(values).split()

1

这应该会有所帮助。不要使用append,而是使用extend+=

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

Output:

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

1
你已经快完成了。现在需要做的就是取消列表的嵌套。
final_result = [x for sublist in new_list for x in sublist]

或者不使用列表推导式:

final_result = []
for sublist in new_list:
    for x in sublist:
        final_result.append(x)

当然,所有这些都可以在一步中完成,而不需要显式地先生成new_list。其他答案已经涵盖了这一点。

你这里没有调用 split - Adam Smith
2
@AdamSmith 我的起点是 OP 的 new_list [['Hello', 'dude'], ['What', 'is', 'your', 'name'], ['My', 'name', 'is', 'Chetan']] - timgeb

1
new_list = [x for y in str for x in y.split(" ")]

1
尝试这个:-
str = ["Hello dude", "What is your name", "My name is Chetan"]
ls = []
for i in str:
    x = i.split()
    ls +=x
print(ls)

0

你可以尝试:

>>> new_list=[]
>>> str = ["Hello dude", "What is your name", "My name is Chetan"]
>>> for row in str:
      for data in row.split():
        new_list.append(data)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接