【发布时间】:2014-01-18 14:39:06
【问题描述】:
我有一个有趣的问题,可以用“用另一种方式做”来很好地回答。
我有一个用 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)
因此,最终结果是列表中任何内容的字典(在此示例中为整数,但并非总是如此),但键指向子字典的某些点除外。这是代码的简化版本,我取出了所有获取键和值的额外代码(我对它进行了广泛的测试),所以我在这里放入字典中的内容看起来有点傻(但模拟了我'做得很好)。感谢您的帮助。
edit:根据要求提供有关输入和输出的更多详细信息。输入是一个字符串列表,主要写成 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}
如果这有意义的话。如果需要更多细节,请告诉我。
【问题讨论】:
-
您可以在全局范围内存储一个变量并在函数内部访问它。这样每次功能完成后就不会浪费了。
-
你能放一个输入/输出样本吗?
-
尝试使用 break 关键字而不是 continue。 Break 将退出 forloop,您的递归函数将返回到前一个。 continue 关键字只是跳过循环的当前迭代并继续下一个。
-
@Christian 更新了帖子。
-
@ConorPatrick 我不一定想退出 for 循环,我只想跳过 X 次迭代,其中 X 是我在子函数中经历的迭代次数。如果我打破了,那么一旦我到达顶层,我就会退出。
标签: python list for-loop recursion dictionary