2017-10-11 95 views
0
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' }錯誤的輸出產生無法獲得正確的輸出

回答

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) 

輸出:{ '加布裏埃爾': '44', '賈尼絲': '22', '喬伊': '21', '席恩': '33'}

1

你總是變老[0]。你應該改變它的年齡[x]