0

我有一个列表,其结构如下:

['Blah blah blah', 'blah blah blah', 'blah', 'blah blah']

(用户输入组成列表的输入,但我已经为此编写了代码)我需要编写一个代码来告诉用户列表中有多少单词。在那个特定的列表中,有 9 个单词,我尝试了很多方法,但我似乎无法编写正确的代码。请帮忙,谢谢。

4

3 回答 3

4

假设单词总是由一个空格分隔,您可以使用以下代码:

>>> words = ['Blah blah blah', 'blah blah blah', 'blah', 'blah blah']
>>> 
>>> sum(len(line.split()) for line in words)
9
于 2013-07-14T20:49:23.340 回答
0
sum(len(x) for x in [w.split() for w in ['Blah blah blah', 'blah blah blah', 'blah', 'blah blah']])
=> 9

或更短,正如 Eric 建议的那样:

sum(len(x.split()) for x in ['Blah blah blah', 'blah blah blah', 'blah', 'blah blah'])
于 2013-07-14T20:49:33.313 回答
0

这应该有效:

thelist = ['Blah blah blah', 'blah blah blah', 'blah', 'blah blah']
wc = 0
for item in thelist:
    words = item.split()
    wc = wc + len(words)
print 'word count is %d.' % (wc)
于 2013-07-14T20:51:20.747 回答