2014-11-05 21 views
0

定列表Python列表,添加所有的單詞連在一起

sentence = [ "Hello" , "World", "Today is a good", "Day"] 

輸出應該是平均水平的話,那麼1.75

我有這個迄今爲止

for k in len(line): // here i am trying to get position 0,1,2,3etc for k 
     total += len(line[k].split()) 
return total/len(line) 

的錯誤是:'int' object is not iterable,我在這個網站上看過同樣的問題,但仍然不明白是什麼問題。什麼是寫這個循環的更好方法?

回答

1

遍歷的位置:

for k in range(len(line)): 

或者,直接遍歷句子片段:

for fragment in line: 
    total += len(fragment.split()) 

或者你可以用生成器表達式取代循環:

total = sum(len(fragment.split()) for fragment in line) 
+0

是的,作品。謝謝! – b8ckwith 2014-11-05 20:51:47

0

替換

for k in len(line): 

for k in range(len(line)): 
0

你可以加入+分割,然後由列表

>>> sentence = [ "Hello" , "World", "Today is a good", "Day"] 
>>> float(len(" ".join(sentence).split()))/len(sentence) 
1.75 

在Python2,你需要讓他們中的一個浮動否則師截斷的長度除以。

+0

這是一個更好的方式來做到這一點,但它比他所尋找的要複雜得多 - 並沒有指出他的代碼中的問題是什麼...... – 2014-11-05 20:53:11

0

鑑於你一句:

sentence = ["Hello", "World", "Today is a good", "Day"] 

你可以把它作爲一個班輪:

print(sum((len(word.split()) for word in sentence))/float(len(sentence))) 

但很容易理解它看看這段代碼:

sentence = ["Hello", "World", "Today is a good", "Day"] 
word_counts = [len(word.split()) for word in sentence] # make a list of word counts 
# [1, 1, 4, 1] 
print sum(word_counts)/float(len(sentence)) 
# 1.75 
相關問題