【问题标题】:how to count spaces of a list in python?如何计算python中列表的空格?
【发布时间】:2021-02-18 15:23:57
【问题描述】:

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

这里的空格数应该是5。

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

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

你能帮帮我吗?

【问题讨论】:

  • v == vocab...?
  • 对不起.. 我把我的名单命名错了。我的列表名称是 Vocab。

标签: python arrays python-3.x string list


【解决方案1】:

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

from collections import Counter

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

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

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

正如@superb rain 所建议的那样,加入所有字符串并使用 count 方法将有利于您的用例。如果您需要一次性计算更多字符串,您可以使用基于计数器的解决方案。

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

【讨论】:

  • 如果有人需要计算多个项目?例如,一次性获取空间计数和字符串“a”。除此之外,我认为计数方法会更好
【解决方案2】:

你需要两个循环来遍历一个单词和单词列表:

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)

【讨论】:

    【解决方案3】:

    使用list comprehensionre.findall统计空格的个数:

    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
    

    【讨论】:

      【解决方案4】:

      您可以计算每个字符串中的空格并 sum() 总数:

      sum(s.count(" ") for s in vocab)  # 5
      

      【讨论】:

        猜你喜欢
        • 2018-09-04
        • 2021-08-05
        • 2017-04-30
        • 1970-01-01
        • 2022-08-18
        • 2019-02-22
        • 2016-06-05
        • 2020-05-25
        • 2022-11-27
        相关资源
        最近更新 更多