Python:有一个类似C的for循环吗?

Cri*_*scu 16 python for-loop

我可以在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

  • 显然,optparse在2.7中被淘汰了,新的味道被称为argparse.他们似乎都能够做我需要的,但我想知道它是否值得学习曲线.无论如何,+1指出这个模块. (3认同)
  • 'optparse`的+1.手动解析命令行参数是完全没有必要的. (2认同)

Net*_*ooc 9

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.

  • @Cristi是,但这是问题中的原始示例代码,所以我认为这就是他想要的. (4认同)

Sil*_*ost 8

您可以通过两件事来解决问题:

  • 需要逗号分隔的参数,这些参数将被分组到以下选项值,您可以使用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)


Cha*_*tie 5

奇怪的方式:

for x in (x for x in xrange(10) if someCondition):
    print str(x)
Run Code Online (Sandbox Code Playgroud)