代码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条经验 获得超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
提交
取消
