1 回答

TA貢獻(xiàn)1836條經(jīng)驗 獲得超5個贊
要使用正則表達(dá)式匹配來解決您的問題 - 使用以下方法:
import re
from collections import defaultdict
my_list = [{'Name': 'Super', 'Gender': 'Male', 'UNNO': 111234},
{'Name': 'Spider', 'Gender': 'Male', 'UNNO': 11123},
{'Name': 'Bat', 'Gender': 'Female', 'UNNO': 113456},
{'Name': 'pand', 'Gender': 'Female', 'UNNO': 13456}]
genders = defaultdict(list)
pat = re.compile(r'^11\d{4}$') # crucial pattern to validate `UNNO` number
for d in my_list:
if pat.search(str(d['UNNO'])):
genders[d['Gender']].append(d['Name'])
print(dict(genders)) # {'Male': ['Super'], 'Female': ['Bat']}
添加回答
舉報