【发布时间】: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