【问题标题】:Would Like to Improve this Script想改进这个脚本
【发布时间】:2018-10-13 08:53:07
【问题描述】:

我正在查看我保存的一些脚本并遇到了这个特定的脚本;我觉得不需要使用所有小写/大写字母就可以改进它,有什么建议吗?我在考虑使用str.lower,但真的不知道如何实现它

def all_but_not_numbs(s: str) -> int:
    """
    >>> all_but_not_numbs('asd123')
    3
    >>> all_but_not_numbs('E.666')
    2
    """

    num_letters = 0

    for char in s: 
        if char in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,':
            num_letters = num_letters + 1
    return num_letters

【问题讨论】:

    标签: python


    【解决方案1】:

    使用str.lower,您可以将要测试的字符小写,这样就不需要大写字母。 ., 的字符不受 lower 的影响。此外,将sum 与生成器表达式一起使用可以使您的代码更紧凑并且(恕我直言)更具可读性。

    >>> letters = "abcdefghijklmnopqrstuvwxyz,."
    >>> s = 'E.666'
    >>> sum(1 for c in s if c.lower() in letters)
    2
    

    或者您可以使用string 模块中定义的ascii_letters

    >>> import string
    >>> letters = string.ascii_letters + ",."
    >>> sum(1 for c in s if c in letters)
    2
    

    不过,在这两种情况下,in 检查都是线性的(对于 k 个“好”字母来说是 O(k))。对于这么短的字母列表,这应该不是问题,但要进一步改进它,您可以将letters 转换为set,这样in 的检查将是O(1)。

    >>> letters = set(letters)
    

    【讨论】:

      【解决方案2】:

      使用regex 查找所有字母和点并取长度:

      import re
      
      s = 'asd123'
      print(len(re.findall(r'[a-zA-Z\.]', s)))
      # 3
      

      【讨论】:

      • 这是一个非常有用的模块
      【解决方案3】:

      您也可以使用以下方法,基本上,剥离数字并使用len 计算剩余字符数:

      >>> s
      'asd123'
      >>> to_strip = '0123456789'
      >>> len(s.strip(to_strip))
      3
      

      或者使用string模块中的string.digits

      >>> s
      'asd123'
      >>> len(s.strip(string.digits))
      3
      

      编辑:在 tobias_k cmets 之后,我建议以下与奥斯汀的答案类似但通过不同的方法:

      >>> s = 'abced@#$%123'
      >>>
      >>> import re
      >>>
      >>> to_strip
      '0123456789'
      >>> re.findall('[^{}]'.format(to_strip), s)
      ['a', 'b', 'c', 'e', 'd', '@', '#', '$', '%']
      >>> len(re.findall('[^{}]'.format(to_strip), s))
      9
      

      它表示要查找除 (^) 之外的所有字符,在 (^) 之后提到的字符是数字。

      【讨论】:

      • 不适用于其他字符,如 $、%、-、*、( 等,如果您扩展要删除的字符列表,您只是在反转 OP 的问题(并使情况变得更糟,要写出更长的字符列表)。另外,strip 不会删除字符串中间的字符。
      • @tobias_k,答案已更新,感谢您的提醒!
      【解决方案4】:

      好吧,我使用了s.isalpha()s.upper.isupper()ch in '.'(不需要,):

      现在,我的问题是为什么 Python 说我的行 if ch.isalpha(): 不一致? 错误:builtins.TabError: inconsistent use of tabs and spaces in indentation

      num = 0
      for ch in s:
          if ch.isalpha():
              num = num + 1
          elif ch.upper.isupper():
              num = num + 1
          elif ch in '.':
              num = num + 1
      return num
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多