Skip to main content
 首页 » 编程设计

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

2024年10月25日8傻小

我是 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 中的 List Comphrehsnios 基本上是编写普通 for 循环的简写形式。

上面可以写成:

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

你知道为什么这行不通吗?

这实际上会遍历字符串 sentence 中的所有字符。

任何你可以用 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]