【发布时间】:2020-04-23 01:17:45
【问题描述】:
我的 JSON 数据如下所示:
data2 = [{'name': '', 'steps': [{'number': 1, 'step': 'Place olive oil on the bottom of your Instant Pot before adding chicken breasts to the Instant Pot.', 'ingredients': [{'id': 4053, 'name': 'olive oil', 'image': 'olive-oil.jpg'}], 'equipment': [{'id': 414093, 'name': 'instant pot', 'image': ''}]}, {'number': 2, 'step': 'Season chicken breast with salt and pepper.', 'ingredients': [{'id': 1102047, 'name': 'salt and pepper', 'image': 'salt-and-pepper.jpg'}], 'equipment': []}, {'number': 3, 'step': 'Close Instant Pot and make sure the pressure gauge is turned to seal. Set pressure to manual, high pressure and set the timer for 8 minutes. Pressure will build and then the timer will start.', 'ingredients': [], 'equipment': [{'id': 414093, 'name': 'instant pot', 'image': ''}, {'id': 404695, 'name': 'kitchen timer', 'image': 'kitchen-timer.jpg'}], 'length': {'number': 8, 'unit': 'minutes'}}, {'number': 4, 'step': 'When the timer goes off, quick release the Instant Pot by turning pressure gauge to vent. When pressure releases shred chicken breast in the Instant Pot and serve any way you like.', 'ingredients': [], 'equipment': [{'id': 414093, 'name': 'instant pot', 'image': ''}, {'id': 404695, 'name': 'kitchen timer', 'image': 'kitchen-timer.jpg'}]}]}]
我想得到数字和步数,这样我的输出打印如下:
1 Place olive oil on the bottom of your Instant Pot before adding chicken breasts to the Instant Pot.
2 Season chicken breast with salt and pepper.
3 Close Instant Pot and make sure the pressure gauge is turned to seal. Set pressure to manual, high pressure and set the timer for 8 minutes. Pressure will build and then the timer will start.
4 When the timer goes off, quick release the Instant Pot by turning pressure gauge to vent. When pressure releases shred chicken breast in the Instant Pot and serve any way you like.
我当前的代码如下:
for item in data2[0]['steps']:
print(item['step'])
这只会打印出所有步骤,而不是数字。我怎样才能打印出“数字”的值呢?
【问题讨论】:
-
尝试项目["number"]
-
你可以这样做:
print(f"{item['number']} {item['step']}") -
或
print(item['number'], item['step']) -
但我必须使用 for 循环
for item in data2[0]['step']才能访问每个项目... -
没问题,上面的代码就可以了。