映射 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)
我正在 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)