【问题标题】:Auto increment of Concatenated alpha-numeric. (Python)连接的字母数字的自动增量。 (Python)
【发布时间】:2011-05-01 19:04:45
【问题描述】:

我已经定义了一个生成 ID 的函数。我需要在每次调用该函数时递增数字。

所以我使用max() 函数来查找存储在列表中的最后一个最大值。 根据要求,我的 ID 还应该由整数前面的字符串组成。

所以我将一个字符串与一些存储在列表中的数字连接起来。

现在我的max() 不起作用,因为在将其转换为字母数字后,请帮忙。我尝试拆分 ID,但拆分了每个字符。

下面是我定义的函数:

#!/usr/bin/python

from DB import *

def Sid():
        idlist = []

        for key in Accounts:
                if Accounts[key]['Acctype'] == 'Savings':
                        idlist.append(Accounts[key]['Accno'])

        if len(idlist) == 0:
                return 1001

        else:
                abc = max(idlist)
                return abc + 1

编辑 1: 这是我调用函数的方式:

  accno = Sid()
  AppendRecord(Accno="SA"+str(accno))

【问题讨论】:

    标签: python auto-increment


    【解决方案1】:

    你可以去掉字符串中的数字后缀,得到一个要递增的数字:

    import re
    
    def number_suffix(s):
        """Return the number from the end of the string. """
        match = re.search(r"\d+$", s)
        if match:
            num = int(match.group(0))
        else:
            num = 0
        return num
    
    print number_suffix("AS1001")    # 1001
    print number_suffix("AS1")       # 1
    print number_suffix("AS")        # 0
    

    然后改变你的功能:

    idlist.append(number_suffix(Accounts[key]['Accno']))
    

    【讨论】:

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