我有一个有趣的问题,很可能用“换一种方式”来回答。
我有一个使用 for 循环遍历列表的函数。我根据某些参数在自身内部调用该函数,并从它所在的位置开始遍历列表。问题是我希望能够跳出递归调用回到顶部函数,但要跟踪我在列表中走了多远并从那里继续。
基本上我想要这样的东西:
def iterate_list(listA)
dictA = {}
for pos,item in enumerate(listA):
if item == 1:
dictA[pos] = iterate_list(listA[pos])
#At this point I want to go back to for loop (like continue does) except I want
#to be at the pos I was at when I left the sub function
continue #? Don't think continue is what I want but its the closest thing I could
#find so I left it in for now
elif item == 2:
return dictA
else:
dictA[pos] = item
return dictA
dictFinal = iterate_list(original_list)
因此,最终结果是列表中任何内容的字典(在本例中为整数,但不总是),除了某些点,当键指向子字典时。这是代码的简化版本,我删除了所有获取键和值的额外代码(我对它进行了广泛的测试)所以我在这里放入字典的内容看起来有点傻(但模拟了我的内容做得很好)。感谢您的帮助。
编辑:根据要求提供更多有关输入和输出的详细信息。输入是一个字符串列表,大部分写成 word : word,输出是第一个词作为键,第二个词作为字典的值。字符串代码的解析已编写并有效。但是有一些重复键的区域,所以我希望将它们放入子字典中。例如
Input = [Name: Bob, ID: 12345, Age: 99, Job: Dentist, Patient Name: John, Patient ID: 321, Patient Name: Susan, Patient ID: 666, Patient Name: Lucy, Patient ID: 087, Employees: 5, Address: 233 Main St, Phone: 555-5555]
Output = {Name : Bob, ID : 12345, Age : 99, Job : Dentist, Patient1 : {Patient Name : John, Patient ID : 321}, Patient2 : {Patient Name : Susan, Patient ID : 666}, Patient3 : {Patient Name : Lucy, Patient ID : 087}, Employees : 5, Address : 233 Main St, Phone : 555-5555}
如果这是有道理的。如果需要更多详细信息,请告诉我。
请您参考如下方法:
一个简单的答案是使用迭代器。如果您将迭代器传递给递归调用并且它消耗了一些元素,则当递归调用返回时,您将从它停止的地方继续:
def function(iterable):
iterable = iter(iterable):
for thing in iterable:
if some_condition(thing):
function(iterable)
continue
# The next iteration of the loop will use
# the first item the recursive call didn't.
不过,这可能不会成功;例如,您可能需要返回列表中的一两个位置,而大多数 Python 迭代器不支持它。在这种情况下,您可以编写一个允许您取消使用元素的迭代器,或者您可以使用显式索引进行迭代并将停止处的索引放入返回值中。
