gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:43:11 25 4
gpt4 key购买 nike

我正在尝试查找单词列表中的字符总数,特别是此列表:

words = ["alpha","omega","up","down","over","under","purple","red","blue","green"]

我尝试过这样做:

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

但这只是告诉我列表中有多少个单词,即 10。

如有任何帮助,我们将不胜感激!

抱歉,我想说的是,我正在执行此操作的类(class)是关于 for 循环的主题,所以我想知道是否必须实现 forloop 才能给我答案,这就是 for 循环标签的原因在那里。

最佳答案

您可以在列表理解中使用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(len(i) for i in words)
43

如果您真的热衷于 for 循环。

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

>>> print total
43

关于python - 在Python中查找列表中所有单词的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25934586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com