我有一个很大的电话号码列表来自number_list(取自文件),需要映射字典中的前缀号码。我如何匹配这两个数字?
number_list = [919865588453, 919613851649, 919869863504]
number_map = {91986 : 'Area 1', 9196138 : {'Area 2'}, 9198698 : 'Area 3'}
for number in number_list:
for partialnum_ref, map_ref in number_map.iteritems():
if re.match(number"\d", partialnum_ref):
print "%d is in %s" % (number, map_ref)
答案 0 :(得分:0)
为什么'Area 2'
在一个集合中?
但是,假设您想要最具体的区域:
number_list = [919865588453, 919613851649, 919869863504, 123456789012]
number_map = {91986 : 'Area 1', 9196138 : 'Area 2', 9198698 : 'Area 3'}
for number in number_list:
for prefix, area in sorted(number_map.items(), key=lambda x: len(x[1])):
if str(number).startswith(str(prefix)):
print "%d is in %s" % (number, area)
break
else:
print "%d is in no area" % number
产生
919865588453 is in Area 1
919613851649 is in Area 2
919869863504 is in Area 3
123456789012 is in no area
如果您想要一个数字所在的所有区域而不是最具体的区域,则可以删除sorted
和break
。