如何在python中计算列表的空格?

2024-05-23 20:07:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,其中应该计算单词之间的空格总数。 例如:
vocab = ['he llo','go ing','home work','play foot ball','spring']

此处的空格数应为5

我使用此代码,但它只计算列表中最后一个单词的空间:

x  = sum(c.isspace() for c in vocab)

你能帮帮我吗


Tags: gohome列表play单词workhe空格
3条回答

使用list comprehension^{}计算空白的数量

import re
vocab = ['he llo','go ing','home work','play foot ball','spring']
num_whitespace = len([w for s in vocab for w in re.findall(r'\s', s)])
print(num_whitespace)
# 5

你可以在循环中使用这样的计数器

from collections import Counter

sum(Counter(x).get(" ", 0) for x in v) # 5

如果您担心重复的计数器调用,您可以加入所有字符串并使用单个计数器调用

Counter("".join(v)).get(" ") # 5

正如@supernerain所建议的,连接所有字符串并使用count方法将有利于您的用例。如果您需要一次计数多个字符串,可以使用基于计数器的解决方案

"".join(v).count(" ")

您需要两个循环来迭代单词和单词列表:

v=['he llo','go ing','home work','play foot ball','spring']
x  = sum(c.isspace() for vocab in v for c in vocab)
print(x)

相关问题 更多 >