2016-01-19 19 views
1

Python新手。不知道我是否以最好的方式表達了這一點,但這裏就是這樣。我有這樣的命令列表:Python從變量(i,20)開始遍歷範圍

cmd_list = [ 
"cmd1", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.2.1", 
".1.3.6.1.4.1.24391.4.1.3.3.1.3.1.4.1", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.3.1", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.4.1", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.5.1", 
"cmd2", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.2.1", 
".1.3.6.1.4.1.24391.4.1.3.3.1.3.1.4.1", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.3.1", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.4.11", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.5.11", 
"cmd3", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.2.12", 
".1.3.6.1.4.1.24391.4.1.3.3.1.3.1.4.12", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.3.12", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.4.12", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.5.12", 
] 

CMD1後的5個值獲得比CMD1,5 CMD2與CMD2,等我試圖通過循環通過以下方式進行迭代,但它不後看起來並不理想。

i=0 
for i in range(i,cmd_list.__len__()): 
    #expect to first see normal command (check it doesn't start with .) 
    i += 1 
    while cmd_list[i].startswith("."): 
     #save these values to a list 
     i += 1 
    #do stuff when I have all the command info 

這適用於第一個,但隨後當for循環遍歷,我又回到1,從5或6或不管它是什麼。

更好的方法來做到這一點?謝謝

+0

'對於我來說,列舉項目(cmd_list):'是一種更好的迭代方式。 'i'將從零開始並自動增加。 'item'是當前迭代的項目,等同於'cmd_list [i]'。也就是說,如果你甚至需要'我';否則,'對於cmd_list中的項目:'。 –

+0

@ user2503227你確定每cmd只有5個命令嗎? –

回答

1

我把它全部變成詞典:

>>> step = 6 
>>> commands = {cmd_list[i]: cmd_list[i+1:i+step] 
       for i in range(0, len(cmd_list), step)} 

然後你可以索引使用命令名稱:

>>> commands['cmd2'] 
[".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.2.1", 
".1.3.6.1.4.1.24391.4.1.3.3.1.3.1.4.1", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.3.1", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.4.11", 
".1.3.6.1.4.1.24391.4.1.3.2.1.2.1.5.11"] 
0

您遇到錯誤,因爲變量索引i不是迭代器對象。它只是範圍內索引的副本。改變它的值不會影響循環。

您可以在每種格式中轉換您的代碼,以便您不必擔心索引。 確保您不會推送到列表正在用於生成器的列表。 對於實例

commands = [] 
command = None 
for cmd in cmd_list: 
    #expect to first see normal command (check it doesn't start with .) 
    if cmd.startswith("."): 
     #save these values to a list 
     commands.append(cmd) 
    else: 
     if command: 
     #do stuff when I have all the command info 
     commands = [] 
     command = cmd 
0

更好的方式來做到這一點?

這裏的清潔劑的一種方法:

for e in cmd_list: 
    if e.startswith("."): 
     #we have values to save to list 
    else: 
     # e is cmd1, cmd2 etc. 

    #do stuff when I have all the command info