生成错误的输出无法获得正确的输出

时间:2017-10-11 02:28:17

标签: python-2.7

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)

输出: {' Gabriel':' 22',' Janice':' 22',' Joey':' 22',' Theon':' 22'}

2 个答案:

答案 0 :(得分:1)

你总是变老[0]。你应该把它改成年龄[x]

答案 1 :(得分:0)

每当你获得第一个元素时。你必须去年龄[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)

输出:{'Gabriel':'44','Janice':'22','Joey':'21','Theon':'33'}