【问题标题】:Count of strings start with particular character字符串计数以特定字符开头
【发布时间】:2017-08-08 12:58:28
【问题描述】:

我正在尝试从以下列表中查找以字母 V 开头的国家/地区计数:

 ['USA', '249', '158', '84', '8.7'],
 ['Uruguay', '115', '35', '220', '6.6'],
 ['Uzbekistan', '25', '101', '8', '2.4'],
 ['Vanuatu', '21', '18', '11', '0.9'],
 ['Venezuela', '333', '100', '3', '7.7'],
 ['Vietnam', '111', '2', '1', '2.0'],
 ['Yemen', '6', '0', '0', '0.1'],
 ['Zambia', '32', '19', '4', '2.5'],
 ['Zimbabwe', '64', '18', '4', '4.7']

代码:

def countCountry(csv1):
    count = 0
    for item in csv1:
        if '/V+' in item[0]:
            count +=1
    return count

不幸的是,count 总是返回零。有人可以帮忙吗?

【问题讨论】:

    标签: python regex python-3.x csv


    【解决方案1】:

    只需sum(1 for row in csv if row[0][0] == 'V')

    【讨论】:

    • 为你的答案添加一些解释,提供更多细节。
    【解决方案2】:

    尝试使用startswith:

    def countCountry(csv1):
        count = 0
        for item in csv1:
            if item[0].startswith('V'):
                count +=1
        return count
    
    print countCountry(a)
    

    或者:

    def countCountry(csv1):
        return sum([True for i in csv1 if i[0].startswith('V')])
    
    print countCountry(a)
    

    【讨论】:

      【解决方案3】:
      if '/V+' in item[0]:
      

      Python 不使用斜杠来表示正则表达式,in 执行精确搜索。按照其他答案的建议,导入并使用 re 或使用 str.startswith()

      【讨论】:

      • 我明白了。谢谢@Ignacio。欣赏它
      • 如果意图只是匹配/^V//V+/ 将是一个非常糟糕的正则表达式
      【解决方案4】:

      为什么您的代码不能按预期工作

      您编写的代码总是返回零计数,因为第 4 行永远不会被评估为 True。第 4 行始终为 False,因为它正在检查 '/V+' 是否正如它所显示的那样是国家/地区的名称 in,但绝不会如此。此外,如果确实存在一个名称像'Japmeri/V+na' 这样古怪的国家,您将收到误报

      1. def countCountry(csv1):
      2.    count = 0
      3.    for item in csv1:
      4.        if '/V+' in item[0]:
      5.            count +=1
      6.    return count
      

      修复

      以下是如何使您的代码更好,我将比以前的答案更进一步,使其更具可读性和健壮性。

      def countCountry(csv1):
          count = 0
          for item in csv1:
              country_name = item[0].lower() # to ensure you're always checking against lowercase
              if country_name.startswith('v'): # so that it's easy to read
                  count +=1
          return count
      

      我希望这能回答您的问题。编码愉快!

      【讨论】:

        【解决方案5】:

        您可以使用startswith

        def countCountry(csv1):
            count = 0
            for item in csv1:
                if item[0].startswith('V'):
                    count +=1
            return count
        

        或者你可以使用正则表达式 re:

        def countCountry(csv1):
            count = 0
            for item in csv1:
                if re.match(r'V', item[0]):
                    count +=1
            return count
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-05-11
          • 1970-01-01
          • 2017-09-20
          • 2023-03-16
          • 1970-01-01
          • 2019-03-20
          • 1970-01-01
          • 2022-11-30
          相关资源
          最近更新 更多