我怎样才能建立一个"nested for-loop generator"?
How can I build a "nested for-loop generator"?
问题
假设我有一个列表 ['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 文件中所有记录的作者并且您知道“他们在哪里”- i.g。你有列表 [records,record,contributors,authors]
您如何编写一个函数来为任意键列表提取此类信息
也许像
这样的递归
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
所做的任何可能需要在迭代中持续存在的状态更改。
问题
假设我有一个列表 ['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 文件中所有记录的作者并且您知道“他们在哪里”- i.g。你有列表 [records,record,contributors,authors]
您如何编写一个函数来为任意键列表提取此类信息
也许像
这样的递归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
所做的任何可能需要在迭代中持续存在的状态更改。