2015-02-09 105 views
0

我需要在運行時創建一個變量。如何做到這一點使用python使用python的宏字符串concat

例如:

for l in self.device.output.split("\n"): 
    r1 = re.match("(?P<phy>(te|gi)+)", l.strip(), re.IGNORECASE) 
    if r1 is not None: 
     s = l.split(' ') 

這裏s會形式:['GigabitEthernet4/0/1', '', '', 'unassigned', '\r']

我需要建立這樣

s[0]_myqueue0 
s[0]_myqueue1 

這樣的變量I可以在程序中稍後分配以上myqueues的值

我該怎麼做?

回答

0

我不確定你在嘗試什麼,有很多方法可以在運行時創建名稱。

最簡單的方法是使用字典和分配鍵要稍後運行功能或代碼段:

code_map = dict() 

# later on in your code 

code_map[s[0]]['myqueue0'] = 'foo' 

這將導致:

>>> print(code_map['GigabitEthernet4/0/1']['myqueue0']) 
foo 
+0

出於某種原因,上面是沒有工作:我得到這個錯誤:文件「monitor_qos.py」,行365,初始化 code_map ['s [0]'] ['myqueue0'] ='foo' KeyError:'s [0]' bash-3.2 $ – 2015-02-09 12:43:34

+0

不要在鍵上添加引號。看看代碼。 – 2015-02-09 13:18:34

+0

我不知道我缺少什麼,但它仍然不起作用:'for self in self.device.output.split(「\ n」): r1 = re.match(「(?p (te | gi )+)「,l.strip(),re.IGNORECASE) 如果r1不是無: s = l.split('') self.ifaces.append(s [0]) self.code_map [s文件「monitor_qos.py」,第928行,在 如果v.initialize(): 文件「monitor_qos.py」[0]] ['myqueue0'] ='foo''回溯(最近調用最後一個): 「monitor_qos.py」第364行初始化 self.code_map [s [0]] ['myqueue0'] ='foo' KeyError:'GigabitEthernet4/0/1' bash-3.2 $ – 2015-02-09 17:17:02