python:一次遍历列表中的两个对象

fox*_*fox 0 python iteration dictionary list

通过 python 调用 SQL 数据库,返回列表中成对字典的输出:

[{'Something1A':Num1A}, {'Something1B':Num1B}, {'Something2A':Num2A} ...]
Run Code Online (Sandbox Code Playgroud)

我想遍历这个列表,但同时拉两个字典。

我知道这for obj1, obj2 in <list>不是正确的方法,但什么是正确的方法?

Jon*_*nts 6

您可以使用 zip 和列表上的迭代器来执行此操作:

>>> dicts = [{'1A': 1}, {'1B': 2}, {'2A': 3}, {'2B': 4}]
>>> for obj1, obj2 in zip(*[iter(dicts)]*2):
    print obj1, obj2


{'1A': 1} {'1B': 2}
{'2A': 3} {'2B': 4}
Run Code Online (Sandbox Code Playgroud)