【发布时间】:2020-01-28 14:01:40
【问题描述】:
我需要使用正则表达式从字典列表中提取手机号码。
只需要从d[num]中提取
字典:
d = [{'name': 'a', 'num': '9134567890','num2':'912311111'},
{'name': 'd', 'num': '9134567890','num2':'5151'},
{'name': 'b', 'num': '0134567890','num2':'51'},
{'name': 'c', 'num': '9034567890','num2':'12'},
{'name': 'm', 'num': '9034590','num2':'13'}
]
- 电话号码是每个字典的键
"num"的值。 - 所有电话号码必须包含 10 位数字。
- 如果电话号码以
91开头,则为'local'。 - 如果电话号码以
01开头,则为'global'。 - 如果电话号码以其他任何开头,则为
'others'。
伪代码:
s = {'locals':[], 'global':[], 'others':[]}
for i in d:
for k,v in i.items():
#if num starts with 91:
#append locals
#elif num starts with 01:
#append to globals
#else:
#append to others
伪代码
for i in my_dict_1:
print ([ v for k,v in i.items() if str(v).startswith('91') if i['num']])
我的预期输出:
{'locals':[a,d], 'global':['b'], 'others':['d']}
由于问题被搁置,我已经解决了问题
s = {'locals':[], 'global':[],'others':[]}
for i in d:
if i['num'].startswith('91'):
s['locals'].append(i['num'])
elif i['num'].startswith('01'):
s['global'].append(i['num'])
else:
s['others'].append(i['num'])
s
出来
{'global': ['0134567890'],
'locals': ['9134567890', '9134567890'],
'others': ['9034567890', '9034590']}
【问题讨论】:
-
我不清楚它为什么被搁置。虽然措辞不好,可能是由于语言限制(原帖已被编辑),但我相信它确实有足够的细节来提供足够的答案。它并没有问多个问题。相反,它对一个问题提出了多个条件。
-
你快到了。只需删除第二个
for循环并将第一个if语句替换为if i[num].startswith('91'): s['locals'].append(i[num])其他将类似。
标签: python regex list dictionary