首页 > 解决方案 > 理解列表中的双变量嵌套循环

问题描述

我正在尝试通过实现理解列表来改进我的代码。

我有以下声明。

test = [expression.match(self.sourceModel().index(source_row, column, source_parent).data())
                for expression in liste for liste, column in self._filters.items()]

测试是字符串之间的正则表达式匹配,来自表达式列表,包含在 dict 中的列表,列作为键,表达式列表作为值

我不明白为什么我的变量“liste”被标记为未引用,因为它在最后一个 for 循环中被提及,有什么想法吗?

标签: loopsnestedlist-comprehensionnested-loops

解决方案


代码

test = [expression.match(self.sourceModel().index(source_row, column, source_parent).data()) for expression in liste for liste, column in self._filters.items() for expression in liste ]

解释

您的liste变量未被引用,因为您在循环中引用了 liste 变量,该循环仅在您使用 var 本身后执行!

item请记住,在定义之前,然后是定义,认为列表理解是一个颠倒的结构是正确的loop,但是在每个部分中,逻辑顺序与正常循环代码相同


推荐阅读