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

标签 python list functional-programming list-comprehension leading-zero

简单情况:对于给定的字符串输入(如“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方法是什么?它可能是一个接受开始、结束和字母输入的函数,但它必须考虑 leading zeros ,以及字母可以位于数字前面或后面的事实。

最佳答案

我不确定是否有更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']

关于从输入地址范围(如 1-12A)创建地址字母​​/数字列表的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40119867/

相关文章:

python - 在Python中,如何知道对象是否可以比较?

python - 向嵌套列表的字典中插入一个值

Java - 列表、类型和继承(也许是通用的?)

list - Vaadin:在表中显示列表

python - 如何在 mongoengine 中迭代数据库中的集合?

python - 如何在 matplotlib 中根据 x、y、z 坐标绘制等高线图? (plt.contourf 或 plt.contour)

python - "Least Astonishment"和可变默认参数

c++ - 具有棘手的 lambda 表达式的奇怪未定义行为

functional-programming - ELM 以字符串形式获取查询参数

javascript - 将json转换为其他json结构