在Python中查找列表中所有单词的字符数 [英] Finding the amount of characters of all words in a list in Python
问题描述
我正在尝试在单词列表(特别是该列表)中查找字符总数:
I'm trying to find the total number of characters in the list of words, specifically this list:
words = ["alpha","omega","up","down","over","under","purple","red","blue","green"]
我尝试做:
print "The size of the words in words[] is %d." % len(words)
但这只是告诉我列表中有10个单词.
but that just tells me how many words are in the list, which is 10.
任何帮助将不胜感激!
对不起,我的意思是要提到我正在为此做的类是关于for循环的,所以我想知道我是否必须实现forloop才能给我答案,这就是为什么for循环标记在那儿.
Sorry, I meant to mention that the class I'm doing this for is on the topic of for loops, so I was wondering if I had to implement a forloop to give me an answer, which is why the for loop tags are there.
推荐答案
您可以在列表推导中使用len
函数,这将创建一个长度列表.
You can use the len
function within a list comprehension, which will create a list of lengths
>>> words = ["alpha","omega","up","down","over","under","purple","red","blue","green"]
>>> [len(i) for i in words]
[5, 5, 2, 4, 4, 5, 6, 3, 4, 5]
然后使用生成器表达式简单地sum
Then simply sum
using a generator expression
>>> sum(len(i) for i in words)
43
如果您真的在for
循环上放下心来.
If you really have your heart set on for
loops.
total = 0
for word in words:
total += len(word)
>>> print total
43
这篇关于在Python中查找列表中所有单词的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!