代碼ralph = {'type': 'cat','owner': 'mark'}lucy = {'type': 'cat','owner': 'carrie'}pets = [ralph, lucy]for pet in pets: print(str(pet)) owner = pet['owner'] print('pet type: ' + pet['type'] + '\n' + 'owner: ' + owner.title())提供輸出:{'type': 'cat', 'owner': 'mark'}pet type: catowner: Mark{'type': 'cat', 'owner': 'carrie'}pet type: catowner: Carrie我試圖打印每只寵物的名字(拉爾夫和露西)
1 回答

慕哥6287543
TA貢獻1831條經(jīng)驗 獲得超10個贊
您正在嘗試訪問變量名稱。雖然這在原則上是可能的,但您不想這樣做。
我假設你正在嘗試這樣的想法:
pet1 = {'type': 'cat','owner': 'mark', 'name': 'ralph'}
pet2 = {'type': 'cat','owner': 'carrie', 'name': 'lucy'}
pets = [pet1, pet2]
for pet in pets:
print('pet name: ' + pet['name'])
添加回答
舉報
0/150
提交
取消