从输入地址范围(如112A)创建地址字母/数字列表的Pythonic方法

2024-04-25 07:07:02 发布

您现在位置:Python中文网/ 问答频道 /正文

简单的例子:对于一个给定的字符串输入,比如'1-12A',我想输出一个列表,比如

['1A', '2A', '3A', ... , '12A']

这很简单,我可以使用如下代码:

import re

input = '1-12A'

begin = input.split('-')[0]                   #the first number
end = input.split('-')[-1]                    #the last number
letter = re.findall(r"([A-Z])", input)[0]     #the letter

[str(x)+letter for x in range(begin, end+1)]  #works only if letter is behind number

但有时我会遇到输入像“B01-B12”的情况,我希望输出像这样:

['B01', 'B02', 'B03', ... , 'B12']

现在的挑战是,创建一个函数以从上面两个输入中的任何一个建立这样的列表的最python的方法是什么?它可能是一个接受begin、end和letter输入的函数,但是它必须考虑到leading zeros,以及字母可以在数字前面或后面的事实。你知道吗


Tags: the函数字符串代码renumber列表input
1条回答
网友
1楼 · 发布于 2024-04-25 07:07:02

我不确定是否有一种更为pythonic的方法,但是使用一些regex和python的^{}语法,我们可以相当容易地处理您的输入。这里有一个解决方案:

import re

def address_list(address_range):
    begin,end = address_range.split('-')     
    Nb,Ne=re.findall(r"\d+", address_range)

    #we deduce the paading from the digits of begin
    padding=len(re.findall(r"\d+", begin)[0]) 

    #first we decide whether we should use begin or end as a template for the ouput
    #here we keep the first that is matching something like ab01 or 01ab
    template_base = re.findall(r"[a-zA-Z]+\d+|\d+[a-zA-Z]+", address_range)[0]

    #we make a template by replacing the digits of end by some format syntax
    template=template_base.replace(re.findall(r"\d+", template_base)[0],"{{:0{:}}}".format(padding))

    #print("template : {} , example : {}".format(template,template.format(1)))

    return [template.format(x) for x in range(int(Nb), int(Ne)+1)]  

print(address_list('1-12A'))
print(address_list('B01-B12'))
print(address_list('C01-9'))

输出:

['1A', '2A', '3A', '4A', '5A', '6A', '7A', '8A', '9A', '10A', '11A', '12A']
['B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B09', 'B10', 'B11', 'B12']
['C01', 'C02', 'C03', 'C04', 'C05', 'C06', 'C07', 'C08', 'C09']

相关问题 更多 >