我正在编写一个需要找到最近的交换机的电缆映射脚本。因此,如果配线架位于机架 08AB 中,并且机架 08AC 和 08AD 中有开关,我需要它来选择最近的(08AC)。问题是机架编号顺序。前两位数字将始终相同 (08),并且字母递增。但是他们先增加 AZ,然后再增加 AA-AZ。因此,如果面板在机架 08Z 中,则 08AA 比 08X 更接近。
我通过将字母转换为数字并查看哪个最接近,但它看起来很笨重,我想知道是否有更好的方法:
###CLOSEST SWITCH IS IN 08AA
full_panel_location = '08Z'
full_switches_location = ['08X', '08AA']
switches_checksum = []
###REMOVE DIGITS AND CONVERT LETTERS TO CHECKSUM
panel_letters = ''.join([i for i in full_panel_location if not i.isdigit()])
panel_checksum = int(reduce(lambda x,y:x+y, map(ord, panel_letters)))
if panel_checksum > 100:
panel_checksum -= 39
for switch in full_switches_location:
switch_letters = ''.join([i for i in switch if not i.isdigit()])
switch_checksum = int(reduce(lambda x,y:x+y, map(ord, switch_letters)))
if switch_checksum > 100:
switch_checksum -= 39
switches_checksum.append(switch_checksum)
###FIND CLOSEST CHECKSUM/INDEX/SWITCH
closest_switch_checksum = min(switches_checksum, key=lambda x: abs(x - panel_checksum))
closest_switch_index = switches_checksum.index(closest_switch_checksum)
closest_switch = full_switches_location[closest_switch_index]
这提供了最接近的开关是 08AA,这正是我想要的。我的问题是,有没有更好的方法来做到这一点?