如何构建“嵌套 for 循环生成器”?

时间:2021-06-24 14:14:24

标签: python loops iterator

问题

假设我有一个类似 ['key1','key2', ... ,'keyN'] 的列表和一个函数 f()f() 跟随签名 bar = f(foo,key),其中 foo & bar 是可迭代的任意对象。

如何按照以下结构生成嵌套 for 循环(假设任意键和键数量):

for x1 in f(root,key1):
    for x2 in f(x1,key2):
        ...
            for xN in f(xN-1,keyN):
                # some code here
                pass

示例

当我尝试优雅地抓取 xml 文件时,我偶然发现了这一点。 假设您有一个结构如下的 xml 文件:

<xml>
 <records>
   <record>
     <contributors>
       <authors>
         <author>A</author>
         <author>B</author>
         <author>C</author>
       </authors>
     </contributors>
     ...
   </record>
   ...
  </records>
  ...
</xml>

并且您想提取 xml 文件中所有记录的作者,并且您知道“他们在哪里” - 例如你有列表[records,record,contributors,authors] 你如何编写一个函数来为任意键列表提取这种信息

1 个答案:

答案 0 :(得分:3)

也许是递归的东西

def with_keys(node, keys):
    if not keys:
        #some code

    current_key = keys[0]
    next_keys = keys[1:]

    for x in f(node, current_key):
        with_keys(x, next_keys)


with_keys(root, ['key1', 'key2', 'key3'])

这只是一个粗略的草图,因为它没有考虑 # some code 所做的可能需要在迭代中持续存在的任何状态更改。