我可以在Python中做这样的事吗?
for (i = 0; i < 10; i++):
if someCondition:
i+=1
print i
Run Code Online (Sandbox Code Playgroud)
我需要能够根据条件跳过一些值
编辑:到目前为止,所有解决方案都建议根据已知条件以这种或那种方式修剪初始范围.这对我没用,所以让我解释一下我想做什么.
我想手动(即没有getopt)解析一些cmd行args,其中每个'keyword'都有一定数量的参数,如下所示:
for i in range(0,len(argv)):
arg = argv[i]
if arg == '--flag1':
opt1 = argv[i+1]
i+=1
continue
if arg == '--anotherFlag':
optX = argv[i+1]
optY = argv[i+2]
optZ = argv[i+3]
i+=3
continue
...
Run Code Online (Sandbox Code Playgroud)
sbe*_*rry 21
是的,我就是这样做的
>>> for i in xrange(0, 10):
... if i == 4:
... continue
... print i,
...
0 1 2 3 5 6 7 8 9
Run Code Online (Sandbox Code Playgroud)
编辑
根据原始问题的更新...我建议你看一下optparse
for (i = 0; i < 10; i++)
if someCondition:
i+=1
print i
Run Code Online (Sandbox Code Playgroud)
在python中会写成
i = 0
while i < 10
if someCondition
i += 1
print i
i += 1
Run Code Online (Sandbox Code Playgroud)
你去了,就是如何在python中编写ac for loop.
您可以通过两件事来解决问题:
getopt,或者任何其他模块.或做更脆弱的自己处理:
sys.argv.pop()
cmd = {}
while sys.argv:
arg = sys.argv.pop(0)
if arg == '--arg1':
cmd[arg] = sys.argv.pop(0), sys.argv.pop(0)
elif:
pass
print(cmd)
Run Code Online (Sandbox Code Playgroud)奇怪的方式:
for x in (x for x in xrange(10) if someCondition):
print str(x)
Run Code Online (Sandbox Code Playgroud)