使用Python3 for循环枚举对象并打印属性

使用Python3 for循环枚举对象并打印属性,python,python-3.x,Python,Python 3.x,我正在使用Python 3.7.2。我有这样一个JSON对象: cars = {'cars' : [ {'id': '1', 'language': 'en', 'carDescription': 'this car is nice'}, {'id': '2', 'language': 'en', 'carDescription': 'this is a blue Ford'}, {'id': '3', 'language': 'en', 'carDescription': 't

我正在使用Python 3.7.2。我有这样一个JSON对象:

cars = {'cars' : [
  {'id': '1', 'language': 'en', 'carDescription': 'this car is nice'},
  {'id': '2', 'language': 'en', 'carDescription': 'this is a blue Ford'},  
  {'id': '3', 'language': 'en', 'carDescription': 'this is a red Chevy'}
  ]}
# print car id and carDescription
for num, sentence in enumerate(cars['cars'], start=0):
  print("Car {} : {}".format(num, cars['cars'][num]['carDescription']))
我想打印出汽车的ID和描述,我这样做:

cars = {'cars' : [
  {'id': '1', 'language': 'en', 'carDescription': 'this car is nice'},
  {'id': '2', 'language': 'en', 'carDescription': 'this is a blue Ford'},  
  {'id': '3', 'language': 'en', 'carDescription': 'this is a red Chevy'}
  ]}
# print car id and carDescription
for num, sentence in enumerate(cars['cars'], start=0):
  print("Car {} : {}".format(num, cars['cars'][num]['carDescription']))
但是,由于“num”从0开始,“num”总是在实际id后面1

但是,如果我更改start=1,它确实会从1开始计数,但它会跳过第一行,只打印2和3,并且在最后也会出现此错误:

索引器:列表索引超出范围

我怎样才能让它打印出id和相关的cardDescription而不出现错误


顺便说一句,我知道我还没有使用“句子”。

为什么不使用
id
作为索引本身呢?使用
f
-字符串,并且您的Python版本支持该字符串,您可以执行以下操作:

for x in cars['cars']:
    print(f"Car {x['id']}: {x['carDescription']}")

# Car 1: this car is nice
# Car 2: this is a blue Ford                                   
# Car 3: this is a red Chevy

您将num用于两件事:计数和索引

您希望计数从1开始,索引从0开始

Start=1增加num,但它仍然从第0辆车开始计数。换句话说,您仍然会得到三个num(1、2和3)。对于三辆车,num将索引第二辆车(索引1),然后索引第三辆车(索引2),然后由于索引错误而失败,因为索引3处没有第四辆车

试试这个

for num, sentence in enumerate(cars['cars'], start=0):
  print("Car {} : {}".format(num + 1, cars['cars'][num]['carDescription']))

我检查它是否是字典,然后只显示id和汽车描述值

for key,value in enumerate(cars['cars']):
  if isinstance(value,dict):
    for car_key,car_val in value.items():
      if car_key is 'id':
        print("Car ",car_val,end="")
      elif car_key is 'carDescription':
        print(" ",car_val)

对于所有与python相关的问题,请始终使用generic[python]标记。在您的discretionNote中使用特定于版本的标记。在Python中,这不是“JSON对象”。这是一个
命令
。Python中的一切都是对象。要在“cars”键处迭代列表,只需对cars['cars']中的项执行
:打印(项['id',项['carDescription')
当您想要枚举一个iterable时,使用
枚举
。在这种情况下,您不想这样做,您只想遍历dictsthank列表。我正在阅读一些最近的Python3教程,其中指出使用enumerate是在Python中执行循环的更现代的方法。我甚至不知道什么是f字串,但我会去查一查。再次感谢。@SkyeBoniwell,“做循环的现代方式”;不,不一定。如果您的需求不需要访问索引,那么
enumerate
不是正确的选择
f
string只是字符串格式的更新版本;也许你可以称之为“现代方式”。@SkyeBoniwell,enumerate比——对于范围内的i(len(sequence))更“现代”。然而,正如奥斯汀所说,如果不需要索引,那么就不需要枚举或范围。