给定一个包含字母数字的建筑编码列表,要求输出一个 JSON 数据,其中包含每个编码及其对应的描述信息。需要通过列表中的字符值,判断给定的值是否位于指定的范围内。例如,R1-1 到 R10H 之间的任何编码都属于“Residential Districts”。然而,编码的格式可能不同,例如 R1-1 带有连字符,而 R10H 则没有。
2、解决方案
为了解决问题,可以使用正则表达式来检查值是否符合给定范围的格式。以下是改进的代码示例:
import re
def return_code(code):
"""takes in a list of codes and returns a json dictionary of codes and corresponding descriptions"""
data = []
for c in code:
if c.startswith("M") and "R" in c:
#gets mixed Res and Manufacturing districts
data.append({"code": c, "description": "Mixed Manufacturing & Residential Districts"})
elif c.startswith("M") and "R" not in c:
data.append({"code": c, "description": "Manufacturing Districts"})
elif c.startswith("R"):
data.append({"code": c, "description": "Residential Districts"})
elif c.startswith("ZR"):
data.append({"code": c, "description": "Special Zoning District"})
elif c == "ZNA":
data.append({"code": c, "description": "Zoning Not Applicable"})
elif c == "BPC":
data.append({"code": c, "description": "Battery Park City"})
elif c == "PARK":
data.append({"code": c, "description": "New York City Parks"})
elif c == "PARKNYS":
data.append({"code": c, "description": "New York State Parks"})
elif c == "PARKUS":
data.append({"code": c, "description": "United States Parks"})
elif c.startswith("ZR"):
data.append({"code": c, "description": "Special Zoning District"})
else:
# Check if the code falls within a specified range
match = re.match(r'R([1-9]|10)[A-H]?$', c)
if match:
data.append({"code": c, "description": "Residential Districts"})
return json.dumps(data)
在这个改进的代码中,我们使用正则表达式r'R([1-9]|10)[A-H]?$'来检查给定的编码是否符合“Residential Districts”的模式。正则表达式中的 ([1-9]|10)表示匹配数字 1 到 10(包括 10),而 [A-H]?表示匹配可选的字母 A 到 H。如果编码符合这个模式,则将其添加到 JSON 数据中。
以下是使用改进的代码进行测试的示例:
code_list = ["R1-1", "R10H", "M1-2", "ZR 11-151", "ZNA", "BPC", "PARK", "PARKNYS", "PARKUS"]
json_data = return_code(code_list)
print(json_data)
输出结果:
[{"code": "R1-1", "description": "Residential Districts"}, {"code": "R10H", "description": "Residential Districts"}, {"code": "M1-2", "description": "Manufacturing Districts"}, {"code": "ZR 11-151", "description": "Special Zoning District"}, {"code": "ZNA", "description": "Zoning Not Applicable"}, {"code": "BPC", "description": "Battery Park City"}, {"code": "PARK", "description": "New York City Parks"}, {"code": "PARKNYS", "description": "New York State Parks"}, {"code": "PARKUS", "description": "United States Parks"}]