连接字母数字的自动递增。 (Python)

发布于 2024-09-29 07:27:54 字数 747 浏览 2 评论 0原文

我定义了一个生成 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))

I have defined a function that generates ID. I need to increment the numbers every time I call the function.

So I used max() function to find the last largest value stored in the list.
According to the requirements my ID should also consist of a string in front of the integers.

So I have concatenated a string with some numbers which have been stored in a list.

Now my max() does not work,because after concatenating its converted into a alpha-numeric.Please help.I tried splitting the ID but that splits each character.

Following is the function I defined:

#!/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

EDIT 1:
Here is how I have called the function:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

前事休说 2024-10-06 07:27:54

您可以从字符串中去掉数字后缀以获得要递增的数字:

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']))

You can strip off the numeric suffix from the string to get a number to increment:

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

then change your function:

idlist.append(number_suffix(Accounts[key]['Accno']))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文