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
print wordList
1 个回答
2
下面的代码:
wordList = [ x for x in sentence if x!=" "] #using list comprehension
print wordList
不会像你想的那样工作。
在Python中,列表推导式其实就是一种简化写法,用来代替普通的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]