在Python中查找列表中所有单词的字符数量

时间:2014-09-19 13:02:59

标签: python 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。

任何帮助将不胜感激!

抱歉,我的意思是提到我正在做的这个类是关于for循环的主题,所以我想知道我是否必须实现一个forloop来给我一个答案,这就是为什么for循环标签在那里。

3 个答案:

答案 0 :(得分:6)

您可以在列表推导中使用len函数,这将创建一个长度列表

>>> 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

>>> sum(len(i) for i in words)
43

如果你真的把心设置在for循环上。

total = 0
for word in words:
    total += len(word)

>>> print total
43

答案 1 :(得分:0)

假设您在这里有一个单词,并且想要计算一个变量中存在多少个字符。下面的for循环将能够对其进行计数

var = 'Python'

    j = 0
    for i in var:
        j = j + 1
        print(j)

答案 2 :(得分:0)

您只需将其转换为字符串即可。

print(len(str(words)))