2014-09-20 72 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():

​​