0

我有这种类型的 JSON 文档:

{ 
  name : 'John',
  age : 30,
  counts : [
    {day : monday, pay : 75, extra : 33} ,
    {day : tuesday, pay : 69, extra : 12} ,
    {day : sunday, pay : 42, extra : 0}  ]
 }

我想遍历它们并执行操作。我创建了一个变量“a”作为迭代的尝试:

x = [2, 67, 53, 21, 5, ... ... ]

for i in db.docs.find():
    a = 0
    while a <= len(i['counts']):
        ...
        x.append(i['counts'][a]['extra']) 
        ...
        total = ...
        ...
        a = a + 1
        db.docs.update({'id': i['id']}, {'$set':{"counts.a.total":total}})

如何让 Python 接受“a”作为列表索引?感谢您的帮助。

这是错误消息:

Traceback (most recent call last):
    x.append(i['counts'][a]['extra'])
IndexError: list index out of range
4

1 回答 1

0

你可以只使用一个 for 循环:

for element in i['counts']:
    ...
    x.append(element['extra'])

如果必须使用 while 循环,请确保索引严格低于长度。

while a < len(i['counts']):
于 2012-12-03T17:50:54.787 回答