繁体   English   中英

映射python中的开关列表

[英]mapping a list of switches in python

我正在用python写一个mininet拓扑。 我的代码中有一部分应该将开关映射到控制器。 当我一一写下开关和控制器的名称时,它工作正常:

cmap = {'s0': [c0], 's1': [c1], 's2': [c1]}

class MultiSwitch(OVSSwitch):
    "Custom Switch() subclass that connects to different controllers"
    def start(self, controllers):
        return OVSSwitch.start(self, cmap[self.name])

现在想象一下,我有2个开关列表:

switchL1 = [s1, s2, s3]
switchL2 = [s4, s5]

我想使用循环进行此映射,而不是一个接一个地写,这样第一个列表中的开关将连接到一个控制器,而第二个列表中的开关将映射到另一个控制器。

所以应该是这样的:

cmap = {'switchL1': [c0], 'switchL2': [c1]}

class MultiSwitch(OVSSwitch):
    "Custom Switch() subclass that connects to different controllers"
    def start(self, controllers):
        return OVSSwitch.start(self, cmap[self.name])

我怎样才能做到这一点? 我尝试了这段代码:

cmap = {'%s': [c0] % (sw1) for sw1 in range(switches_L1), '%s': [c1] % (sw2) for sw2 in range(switches_L2)}

但是我得到了invalid syntax error

多数民众赞成在无效的字典理解

cmap = {
    **{'%s': [c0] % (sw1) for sw1 in range(switches_L1)},
    **{'%s': [c1] % (sw2) for sw2 in range(switches_L2)}
}

如果要创建2个链接的字典,请分别创建它们,然后使用双星号**表示法将它们解包到新词典中。 格式为:

newdict = {**dict1, **dict2}

问题解决了。 我们可以这样使用:

switchL1 = ['s1', 's2', 's3']
switchL2 = ['s4', 's5']

cmap1={}
cmap2={}
for sw1 in switchL1:
    cmap1[sw1] = [c0]

for sw2 in switchL2:
    cmap2[sw2] = []

cmap={}
cmap.update(cmap1)
cmap.update(cmap2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM