理解与范围界定有一些意想不到的相互作用.这是预期的行为吗?
我有一个方法:
def leave_room(self, uid):
u = self.user_by_id(uid)
r = self.rooms[u.rid]
other_uids = [ouid for ouid in r.users_by_id.keys() if ouid != u.uid]
other_us = [self.user_by_id(uid) for uid in other_uids]
r.remove_user(uid) # OOPS! uid has been re-bound by the list comprehension above
# Interestingly, it's rebound to the last uid in the list, so the error only shows
# up when len > 1
Run Code Online (Sandbox Code Playgroud)
冒着抱怨的风险,这是一个残酷的错误来源.当我编写新代码时,我偶尔会发现由于重新绑定而导致非常奇怪的错误 - 即使现在我知道这是一个问题.我需要制定一个规则,比如"总是用下划线列出列表推导中的临时变量",但即使这样也不是万无一失的.
这种随机定时炸弹等待的事实否定了列表理解的所有"易用性".
Python列表理解语法可以轻松地在理解中过滤值.例如:
result = [x**2 for x in mylist if type(x) is int]
Run Code Online (Sandbox Code Playgroud)
将返回mylist中整数的平方列表.但是,如果测试涉及一些(昂贵的)计算并且您想要对结果进行过滤,该怎么办?一种选择是:
result = [expensive(x) for x in mylist if expensive(x)]
Run Code Online (Sandbox Code Playgroud)
这将导致非"虚假"昂贵(x)值的列表,但是每个x调用两次昂贵的().是否有一种理解语法允许您进行此测试,而每次只调用一次昂贵的一次?