错误的输出产生无法获得正确的输出
问题描述:
import re
NameAge = '''
Janice is 22 and Theon is 33
Gabriel is 44 and Joey is 21
'''
names = re.findall (r'[A-Z][a-z]*', NameAge)
age = re.findall(r'\d{2}', NameAge)
ageDict = {}
x = 0
for eachname in names:
ageDict[eachname] = age[0]
x+=1
print(ageDict)
输出: { '加布里埃尔': '22', '贾尼丝': '22', '乔伊': '22', '席恩': '22' }错误的输出产生无法获得正确的输出
答
每次你提取第一个元素的年龄。你必须去年龄[x]。
NameAge = '''
Janice is 22 and Theon is 33
Gabriel is 44 and Joey is 21
'''
names = re.findall (r'[A-Z][a-z]*', NameAge)
age = re.findall(r'\d{2}', NameAge)
ageDict = {}
x = 0
for eachname in names:
ageDict[eachname] = age[x]
x+=1
print(ageDict)
输出:{ '加布里埃尔': '44', '贾尼丝': '22', '乔伊': '21', '席恩': '33'}
答
你总是变老[0]。你应该改变它的年龄[x]