1

简单案例:对于给定的字符串输入,如“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']

现在的挑战是,创建一个函数以从上述两个输入中的任何一个构建此类列表的最 Pythonic 方式是什么?它可能是一个接受开始、结束和字母输入的函数,但它必须考虑前导零,以及字母可能在数字前面或后面的事实。

4

1 回答 1

2

我不确定是否有更Pythonic的方式来做这件事,但是使用一些正则表达式和 python 的format语法,我们可以相当容易地处理您的输入。这是一个解决方案:

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']
于 2016-10-19T01:03:38.730 回答