【问题标题】:Keeping track of iterations through list done inside function in Python通过 Python 中的函数内部完成的列表跟踪迭代
【发布时间】: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


【解决方案1】:

您好像是parsing 输入列表。列表元素是标记,语法很简单,但语法分析最好使用更多(递归)函数来实现,具体取决于语法定义。

从你的例子来看,BNF 看起来像:

<patient>       ::= <patient-id> <patient-name>  # Patient has 2 fields
<doctor-data>   ::= Name | ID | Age | Job        # Personal doctor data is combination of these data
<doctor>        ::= <doctor-data> <patient>*     # Doctor data is personal data and some patients
<hospital_data> ::= Employees | Address | Phone  # Hospital data fields
<hospital>      ::= <doctor>* <hospital_data>    # Hospital has doctors and additional data

【讨论】:

    【解决方案2】:

    一个简单的答案是使用迭代器。如果您将迭代器传递给递归调用并且它消耗了一些元素,则当递归调用返回时,您将继续从中断处继续:

    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 迭代器不支持这一点。在这种情况下,您可以编写一个允许您取消使用元素的迭代器,或者您可以使用显式索引进行迭代并将您停止的索引放入返回值中。

    【讨论】:

    • 这似乎正是我想要的,完美运行。我得到了一个“可用”的设置,我强制通过循环进行迭代以到达我需要的位置,但这种方式更清洁(虽然我不确定,但我猜想效率更高)。谢谢。
    猜你喜欢
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多