Python列表理解(将句子转换为单词)

Python列表理解(将句子转换为单词),python,Python,我是python新手,有一个简单的疑问 我正在试着理解 我正在尝试将字符串中的单词添加到列表中。但我们不能这样做。我做错了什么 sentence = "there is nothing much in this" wordList = sentence.split(" ") #normal in built function print wordList wordList = [ x for x in sentence if x!=" "] #using list comprehension

我是python新手,有一个简单的疑问

我正在试着理解

我正在尝试将字符串中的单词添加到列表中。但我们不能这样做。我做错了什么

sentence = "there is nothing much in this"

wordList = sentence.split(" ") #normal in built function
print wordList

wordList = [ x for x in sentence if x!=" "] #using list comprehension
print wordList
以下是:

wordList = [ x for x in sentence if x!=" "] #using list comprehension
print wordList
不会像你期望的那样工作

Python中的列表comphrehsnos基本上是编写普通for循环的一种简捷形式

上述内容可以写成:

wordList = []
for x in sentence:
    if x != "":
        wordList.append(x)

print wordList
你明白为什么这行不通吗

这实际上会迭代字符串
语句中的所有字符

使用for循环可以做的任何事情都可以通过列表理解来完成

示例:

xs = []
for i in range(10):
    if i % 2 == 0:
        xs.append(i)
相当于:

xs = [i for i in range(10) if i % 2 == 0]

句子.split(“”)
已经给了你一个单词列表,所以我不确定这里是否有问题。我想知道列表压缩。我试着做同样的事情。我会断言在列表理解中执行句子.split()是完全多余的,因此是不必要的-只有句子.split()就其本身而言,我同意@Ajean——我在这里的回答是试图向OP说明什么是列表理解,以及如何建模和思考如何编写它们。