簡體   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