Python不同字符串列表,将所有单词一起添加

时间:2014-11-05 20:47:57

标签: python list for-loop

给定清单

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,我确实看过这个网站上的同样问题,但仍然不明白是什么问题。编写此循环的更好方法是什么?

4 个答案:

答案 0 :(得分:1)

迭代这些职位:

for k in range(len(line)):

或者,直接迭代句子片段:

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

或者你可以用生成器表达式替换循环:

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

答案 1 :(得分:0)

替换

for k in len(line):

for k in range(len(line)):

答案 2 :(得分:0)

您可以加入+拆分,然后除以列表的长度

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

在Python2中,您需要将其中一个设为浮点数,否则除法将截断。

答案 3 :(得分: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