【问题标题】:Find maximum number in a string list with a specific format在具有特定格式的字符串列表中查找最大数
【发布时间】:2021-11-02 21:37:39
【问题描述】:

使用 Python 3,我有一个表单列表

ls = ["a", "b_0", "b_1", "b_2", "c", "d_0", "d_1"]

我必须找出“b_”之后的最大数字。在这种情况下,所需的输出是 2。

我想出了类似的东西:

import re
p = re.compile("b_(\d+)")
nums = [int(p.match(l).group(1)) for l in ls if p.match(l) is not None]
res_max = max(nums)

但我不喜欢重复两次p.match

实现这一目标的最 Pythonic 方式是什么?

d_后的最大数不保证小于b_后的最大数

我特别需要找出“b_”前缀后的最大数字。我对任何其他前缀之后的最大数量不感兴趣

【问题讨论】:

  • 大多数 Pythonic 方式可能不使用任何模块或导入。
  • 列表中的第一个元素"a"怎么样?还是您的意思是忽略前缀中没有 "b_" 的任何内容?
  • @NielGodfreyPonciano 忽略任何没有 b_ 作为前缀的东西

标签: python python-3.x list integer max


【解决方案1】:

类似...

>>> max([int(i.split('_')[-1]) for i in ls if i.split('_')[-1].isdigit()])
2
>>> 

【讨论】:

  • 我觉得你也需要and i[0]=="b"
  • @not_speshal 我猜没必要。
  • d中的数字不保证小于b中的数字
  • @robertspierre 是的!这就是我的代码所做的:P
【解决方案2】:

你可以试试:

>>> max([int(i.split('_')[1]) for i in ls if i.split('_')[0] == 'b'])
2

【讨论】:

  • 我同意你的观点,但我更喜欢使用 '_' 作为分隔符,因为我猜 a, b, c, d 只是示例。我可以使用startswith
【解决方案3】:

另一种方式:

>>> max(int(i.split("_")[-1]) for i in ls if i.startswith("b_"))
2

【讨论】:

    【解决方案4】:

    在这种情况下,将列表推导扩展为显式列表附加:

    import re
    p = re.compile("b_(\d+)")
    
    nums = []
    for l in ls:
        m = p.match(l)
        if m is not None:
            nums.append(int(m.group(1))
    
    res_max = max(nums)
    

    【讨论】:

      【解决方案5】:

      如果你不喜欢重复,可以使用海象运算符:=

      import re
      
      ls = ["a", "b_0", "b_1", "b_2", "c", "d_0", "d_1"]
      
      p = re.compile(r"b_(\d+)")
      
      max_num = max(int(m[1]) for l in ls if (m := p.match(l)))
      print(max_num)
      

      打印:

      2
      

      【讨论】:

        【解决方案6】:

        你可以试试列表理解-

        ls = ["a", "b_0", "b_1", "b_2", "c", "d_0", "d_1"]
        
        res = max([int(string.split('_')[1]) for string in ls if string.startswith('b_')])
        
        print(res) # 2
        

        【讨论】:

          【解决方案7】:

          这可能是另一种方式

          ls = ["a", "b_0", "b_1", "b_2", "c", "d_0", "d_1"]
          res_max = max([int(i.split('_')[1]) for i in ls if i[0] == 'b'])
          print(res_max)
          

          输出:2

          【讨论】:

            【解决方案8】:

            试试这个:

            max([int(l[-1]) if 'b_' in l else 0 for l in ls])
            # 2
            

            不同答案的运行时间:

            %timeit max([int(l[-1]) if 'b_' in l else 0 for l in ls])
            # 1.56 µs ± 204 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
            
            %timeit max([int(i.split('_')[1]) for i in ls if i[0] == 'b'])
            # 2.06 µs ± 213 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
            
            %timeit max(int(m[1]) for l in ls if (m := re.compile(r"b_(\d+)").match(l)))
            # 6.64 µs ± 91.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
            

            【讨论】:

              【解决方案9】:

              一种方法是嵌套推导:

              import re
              p = re.compile("b_(\d+)")
              nums = [
                  int(m.group(1))
                  for m in (p.match(l) for l in ls)
                  if m is not None
              ]
              res_max = max(nums)
              

              【讨论】:

                【解决方案10】:

                这是使用re.search()的另一种方法

                    import re
                
                    ls = ["a", "b_0", "b_1", "b_2", "c", "d_0", "d_1"]
                    pattern = r'b_(\d+)'
                
                    lst = [res.group(1) for i in ls if (res := re.search(pattern, i))]
                    print(max(lst))
                

                输出:

                    2
                

                在第 6 行,它检查列表 ls 中的每个元素是否与 pattern 匹配,然后将匹配字符串的第一组(即数字)添加到列表 lst

                res := re.search(pattern, i) 部分将re.search(pattern, i) 的值分配给变量res,同时检查它是否为None,然后if 语句将不会激活,如果它有值然后if 语句将被激活。这要感谢“海象操作员”:=

                【讨论】:

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