如何以Pythonic方式处理弱引用列表:过滤失效引用并操作对象
更Pythonic的Weakrefs列表处理方式
你可以通过一次遍历+重新构建列表的方式简化代码,既避免维护额外的移除列表,又能高效完成操作:
new_refs = [] for ref in self.list_of_weak_references_to_UI_controls: control = ref() if control: control.enabled = enable new_refs.append(ref) self.list_of_weak_references_to_UI_controls = new_refs
这种写法的优势:
- 仅遍历一次列表,比原写法的两次遍历效率更高
- 无需手动调用
remove方法(原写法中若列表存在重复引用,remove可能只删除第一个匹配项,存在隐患) - 逻辑更紧凑,直接保留有效引用,同时完成业务操作
如果追求极致简洁,也可以拆分为两步(可读性更好):
# 先处理所有有效UI控件 for ref in self.list_of_weak_references_to_UI_controls: if (control := ref()): control.enabled = enable # 过滤掉失效引用 self.list_of_weak_references_to_UI_controls = [ref for ref in self.list_of_weak_references_to_UI_controls if ref()]
这里用了Python 3.8+的海象运算符:=来减少一次变量赋值,让代码更紧凑。
内容的提问来源于stack exchange,提问作者Dean
相关产品推荐
相关产品推荐

