【问题标题】:Python Iterate over range starting with variable (i,20)Python迭代范围以变量(i,20)开始
【发布时间】:2016-01-19 05:38:57
【问题描述】:

Python 新手。不确定我是否以最好的方式表达了这一点,但就这样吧。我有一个这样的命令列表:

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 进行比较,将 cmd2 之后的 5 个值与 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 循环迭代时,i 从 5 或 6 或任何它返回到 1。

更好的方法来做到这一点?谢谢

【问题讨论】:

  • for i,item in enumerate(cmd_list): 是一种更好的迭代方式。 i 将从零开始并自动递增。 item 是正在迭代的当前项,等效于 cmd_list[i]。也就是说,如果你甚至需要i;否则,for item in cmd_list:.
  • @user2503227 你确定每个 cmd 只有 5 个命令吗?

标签: python list loops for-loop


【解决方案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"]

【讨论】:

    【解决方案2】:

    有更好的方法吗?

    这是一种更简洁的方法:

    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
    

    【讨论】:

      【解决方案3】:

      您遇到错误,因为变量索引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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-10
        • 1970-01-01
        • 1970-01-01
        • 2015-12-01
        相关资源
        最近更新 更多