【问题标题】:Need to generate serial number需要生成序列号
【发布时间】:2020-07-14 08:41:41
【问题描述】:

我需要在 Python 或 Shell 脚本中生成 4 个字符的序列号,如下所示。

Serial number should start from 0001, 0002..... when reached 999 it should generate A001,A002....A999, then B001, so on.

我在 Python 中尝试了下面的代码,但它没有完全工作,在几个数字后它开始生成 5 个字符..

def excel_format(num):
    res = ""
    while num:
        mod = (num - 1) % 26
        res = chr(65 + mod) + res
        num = (num - mod) // 26
    return res

def full_format(num, d=3):
    set_flag = 0
    chars = num // (10**d-1) + 1 # this becomes   A..ZZZ
    if len(excel_format(chars)) >= 2:
        set_flag = 1
    if len(excel_format(chars)) > 2:
        set_flag = 2

    if set_flag == 1:
        d = 2

    chars = num // (10 ** d - 1) + 1  # this becomes   A..ZZZ
    digit = num %  (10**d-1) + 1 # this becomes 001..999
    return excel_format(chars) + "{:0{}d}".format(digit, d)

if __name__ == '__main__':
    for i in range(1,10001):
        unique_code = full_format(j, d=3)
        print('Unique Code is =>', unique_code)

【问题讨论】:

  • 我们无法帮助您编写代码,但我们可以帮助您解决您遇到的困难!所以请向我们展示你的努力。

标签: python-2.7 ksh


【解决方案1】:

对 Python 不够熟悉,但你已经标记了 ksh

#!/bin/ksh

typeset -Z3 sn

Letter=( 0 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z )


Index=0

while [[ $Index -lt 28 ]]; do
    sn=0
    while [[ $sn -lt 1000 ]]; do
        print ${Letter[$Index]}$sn
        ((sn++))
    done
    ((Index++))
done

【讨论】:

  • 谢谢,但它无法按预期工作。它在循环中创建了非唯一数字...
  • 这不是你要求的吗?抱歉,那么不确定是否理解您的问题。
【解决方案2】:

此 Python 代码将生成所需的 4 字符(Unique_code)序列号:

#!/usr/bin/python3
import re

for i in range(1,10000):
    if (i < 1000):
       print ("i =", str(i).zfill(4))
    else:
       m = re.findall(r'(\d)(\d\d\d)', str(i))
       code = 64+int(m[0][0])
       print ("i =",i, "Unique_code =", chr(code) + m[0][1])

输出摘录:

i = 0001
i = 0002
...
i = 0999
i = 1000 Unique_code = A000
i = 1001 Unique_code = A001
i = 1002 Unique_code = A002
...
i = 1997 Unique_code = A997
i = 1998 Unique_code = A998
i = 1999 Unique_code = A999
i = 2000 Unique_code = B000
i = 2001 Unique_code = B001
i = 2002 Unique_code = B002
i = 2003 Unique_code = B003
...
i = 9997 Unique_code = I997
i = 9998 Unique_code = I998
i = 9999 Unique_code = I999

【讨论】:

    猜你喜欢
    • 2014-03-17
    • 1970-01-01
    • 2010-12-29
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    相关资源
    最近更新 更多