2014-09-20 73 views
1

我在计算列表中的单词时遇到了麻烦。从Python列表中获取字数

My_list = ["white is a colour", "orange is a fruit", "blue is a mood", "I like candy"] 

我需要输出的脚本是列表中的单词数(在这种情况下为15)。

len(My_list) 

将返回“4”(项目数)。

for item in My_list: 
    print len(item.split()) 

会给我每个项目的长度。

有没有办法从列表中获取字数? 理想情况下,我还想将每个单词追加到新列表中(每个单词都是一个项目)。

回答

2

可以产生的所有的单个单词的列表:

words = [word for line in My_list for word in line.split()] 

只是算的话,使用sum()

sum(len(line.split()) for line in My_list) 

演示:

>>> My_list = ["white is a colour", "orange is a fruit", "blue is a mood", "I like candy"] 
>>> [word for line in My_list for word in line.split()] 
['white', 'is', 'a', 'colour', 'orange', 'is', 'a', 'fruit', 'blue', 'is', 'a', 'mood', 'I', 'like', 'candy'] 
>>> sum(len(line.split()) for line in My_list) 
15 
+0

大,非常有帮助,谢谢! – Zlo 2014-09-20 18:12:14

2

要查找的单词的总和中的每一项:

sum (len(item.split()) for item in My_list) 

把所有的话到一个列表:

sum ([x.split() for x in My_list], []) 
0

你总是可以去的简单循环。

My_list = ["white is a colour", "orange is a fruit", "blue is a mood", "I like candy"] 

c = 0 
for item in My_list: 
    for word in item.split(): 
     c += 1 

print(c) 
0
My_list = ["white is a colour", "orange is a fruit", "blue is a mood", "I like candy"] 

word_count = 0 
for phrase in My_list: 
    # increment the word_count variable by the number of words in the phrase. 
    word_count += len(phrase.split()) 

print word_count 
1

列表理解是一个非常好的主意。另一种方法是使用加入和分割:

l = " ".join(My_list).split() 

现在,“L”是与所有的字标记为项目的清单,你可以简单的使用就可以了LEN():

​​