Python - 循环遍历列表并修改变量

时间:2018-04-06 21:56:07

标签: python python-2.7 loops

我有一个需要帮助的小脚本。基本上它是一个登录到Cisco交换机的脚本,并建议可以使用哪些vlan。例如,如果用户想要添加vlan 10.脚本将查看vlan表并确定vlan 10是否可用,如果是,则成功。如果没有,第一次迭代它将附加1到10并将其设为101.然后它通过并检查101是否可用,如果它也已经在使用,这次它增加1,因此101将变为102, 103,依此类推,直到它有一个未使用的vlan(在列表中)。

我的问题是我得到了这个" 10,101,1012,10123等等。

它应该是这样的: 10,101,102,103等......

我对一些变量进行了硬编码以使脚本变得简单,请看一下:

# Hard coded vlan and vlan_list for testing     
vlan_list = ["1","11", "10", "20", "30", "101", "102", "103", "1011", "1012", "10123", "10111"]
vlan = "10"
# Print what first vlan user has chosen       
print "Vlan is: " + vlan
# If vlan is already in list, append 1. Example: if vlan 10 is already in list, the new vlan would be 101.
#and if 101 is also in vlan_lits, this time increment the newly added 1 like, 102, 103 and so on until it finds a # thats not in vlan_list     
initial = 0
while vlan in vlan_list:
    print "Vlan " + vlan + " is already in use, creating new vlan ..."
    initial = initial + 1
    str_initial = str(initial)
    vlan = vlan  + str_initial  
    print "Vlan chosen is: " + vlan

print "Vlan " + vlan + " is available to use"

我知道我做错了什么,但我无法找到解决问题的方法,所以它的工作原理如上所述。如何编辑循环以获得所需的结果?

由于 Zohaib

2 个答案:

答案 0 :(得分:1)

又快又脏:

while vlan in vlan_list:
    print "Vlan " + vlan + " is already in use, creating new vlan ..."
    initial = initial + 1
    if initial <= 1:
        str_initial = str(initial)
        vlan = vlan  + str_initial
    else:
        vlan = str(int(vlan) + 1)
    print "Vlan chosen is: " + vlan

问题是你第一次应该追加号码,其他时候你不应该。通过添加检查它应该工作,因为初始时它只是第一次通过。

当值超过9(2位数)时,它会“溢出”到数字的其余部分!之后所需的行为是什么?

答案 1 :(得分:1)

您只想追加“1”一次,这样该部分就不应该循环。

if vlan in vlan_list:
    print "Vlan " + vlan + " is already in use, creating new vlan ..."
    vlan = vlan + "1"
    print "Vlan chosen is: " + vlan
    while vlan in vlan_list:
        print "Vlan " + vlan + " is already in use, creating new vlan ..."
        vlan = str(int(vlan) + 1)
        print "Vlan chosen is: " + vlan