【问题标题】:Python looking to find an easier way to shorten my .casefold().count()Python 正在寻找一种更简单的方法来缩短我的 .casefold().count()
【发布时间】:2023-03-23 15:04:02
【问题描述】:

我的 python 代码运行良好,但代码看起来有点乏味和混乱。我想知道是否有更简单的方法来编写它。我有一个文本文件,我需要查找是否可以在行内找到字母“aardvark”。

if i.casefold().count('a') >= 3 and i.casefold().count('r') >= 2 and i.casefold().count('d') >= 1 and i.casefold().count('v') >= 1 and i.casefold().count('k') >=1:

【问题讨论】:

    标签: python-3.x count case-folding


    【解决方案1】:
    if all(
     i.casefold().count(letter) >= 'aardvark'.count(letter)
     for letter in 'aardvark')
    

    有点愚蠢的解决方案,但它有效

    【讨论】:

      【解决方案2】:

      这是一个解决方案的交互式演示:

      >>> i = 'this is a test'
      >>> all(i.casefold().count(x) >= y for x,y in [('a',3), ('r',2), ('d', 1), ('v',1)])
      False
      
      >>> i = 'ardv'*4
      >>> i
      'ardvardvardvardv'
      
      >>> all(i.casefold().count(x) >= y for x,y in [('a',3), ('r',2), ('d', 1), ('v',1)])
      True
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-23
        • 1970-01-01
        • 2021-11-03
        • 2020-08-28
        • 1970-01-01
        • 1970-01-01
        • 2019-05-04
        • 1970-01-01
        相关资源
        最近更新 更多