相关疑难解决方法(0)

即使在理解范围之后,列表理解也会重新命名.这是正确的吗?

理解与范围界定有一些意想不到的相互作用.这是预期的行为吗?

我有一个方法:

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 binding list-comprehension

116
推荐指数
3
解决办法
1万
查看次数

在Python中没有[]的列表理解

加入清单:

>>> ''.join([ str(_) for _ in xrange(10) ])
'0123456789'
Run Code Online (Sandbox Code Playgroud)

join 必须采取迭代.

显然,join这个论点是[ str(_) for _ in xrange(10) ],这是一个列表理解.

看这个:

>>>''.join( str(_) for _ in xrange(10) )
'0123456789'
Run Code Online (Sandbox Code Playgroud)

现在,join这个论点只是str(_) for _ in xrange(10),不[],但结果是一样的.

为什么?是否str(_) for _ in xrange(10)也会产生一个列表或一个可迭代?

python list-comprehension

76
推荐指数
4
解决办法
1万
查看次数

标签 统计

list-comprehension ×2

python ×2

binding ×1