for i in range(4):
for j in V[i].customers:
V[i].message =
dict([(k,array([1,1]))
for k in V[i]. customers])
我完全不理解结构。有人可以解释这是如何工作的吗?
另外, =
是什么?
该行读取有些混乱,因为作者选择使用 line-continature Escapes 。没有这些线路很容易阅读:
for i in range(4):
for j in V[i].customers:
V[i].message = dict((k, array([1,1])) for k in V[i].customers)
我还删除了列表的理解,没有它,代码更快。dict()
调用中的循环现在为发电机表达式,它会为dict()
生成(key, value)
元组对变成字典。
因此,对于4种不同的V[i].customers
序列,相应的V[i].message
属性反复设置为同一字典。这是没有用的,因为j
甚至都没有使用,因此for j
循环可以删除:
for i in range(4):
V[i].message = dict((k, array([1,1])) for k in V[i].customers)
接下来,如果仅V
具有四个索引,则可以直接通过V
替换range()
:
for v in V:
v.message = dict((k, array([1,1])) for k in v.customers)
并且该代码旨在在Python 2.7或更新的情况下运行(因此,如果Python 2.6兼容性不是要求),则可以用A dictionary consection :
替换后者。for v in V:
v.message = {k: array([1,1]) for k in v.customers}