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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25934586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:50:01  来源:igfitidea点击:

Finding the amount of characters of all words in a list in Python

pythonlist

提问by Ryan Ross

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 循环标签在那里。

采纳答案by Cory Kramer

You can use the lenfunction within a list comprehension, which will create a list of lengths

您可以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 sumusing a generator expression

然后简单地sum使用生成器表达式

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

If you really have your heart set on forloops.

如果你真的很喜欢for循环。

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

>>> print total
43

回答by Pragnesh Panchal

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)

回答by Akiva

you can simply convert it to string.

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

print(len(str(words)))