简体   繁体   English

在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"]

I've tried doing:我试过这样做:

print "The size of the words in words[] is %d." % len(words)

but that just tells me how many words are in the list, which is 10.但这只是告诉我列表中有多少个单词,即 10 个。

Any help would be appreciated!任何帮助,将不胜感激!

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.抱歉,我想提一下我正在执行的类是关于 for 循环的,所以我想知道是否必须实现一个 forloop 来给我一个答案,这就是 for 循环标签存在的原因。

You can use the len function within a list comprehension, which will create a list of lengths您可以在列表len中使用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]

Then simply sum using a generator expression然后简单地使用生成器表达式sum

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

If you really have your heart set on for loops.如果你真的很喜欢for循环。

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

>>> print total
43

您可以简单地将其转换为字符串。

print(len(str(words)))

Suppose you have a word here and you want to count how many characters are present in a variable.假设您在这里有一个单词,并且您想计算变量中存在的字符数。 The for loop below will be able to count that下面的 for 循环将能够计算出

var = 'Python'

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM