Python:有没有类似C的for循环可用? [英] Python: is there a C-like for loop available?

查看:643
本文介绍了Python:有没有类似C的for循环可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for(i = 0; i <10; i ++):我可以在Python中做这样的事吗? 
if someCondition:
i + = 1
print i

需要能够跳过一些基于条件的值编辑:到目前为止所有的解决方案建议修剪的初始范围以这种或那种方式,基于已知的条件。这对我没有用,所以让我解释一下我想做的事情。

我想手动(即没有getopt)解析一些cmd行参数,关键字'有一定数量的参数,如下所示:

 对于范围内的(0,len(argv)): 
arg = argv [i]
如果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

...


解决方案

有两件事可以解决您的问题:


  • 需要逗号分隔参数将被分组到以下选项值中,那么可以使用 getopt 或任何其他模块。

  • 或做更脆弱的自己处理:

    pre $ sys $ argv.pop
    cmd = {}
    while sys.argv:
    arg = sys.argv.pop(0)
    如果arg =='--arg1':
    cmd [arg] = sys.argv.pop(0),sys.argv.pop(0)
    elif:
    pass
    print(cmd)



Can I do something like this in Python?

for (i = 0; i < 10; i++):
  if someCondition:
     i+=1
  print i

I need to be able to skip some values based on a condition

EDIT: All the solutions so far suggest pruning the initial range in one way or another, based on an already known condition. This is not useful for me, so let me explain what I want to do.

I want to manually (i.e. no getopt) parse some cmd line args, where each 'keyword' has a certain number of parameters, something like this:

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

    ...

解决方案

There are two things you could do to solve your problem:

  • require comma-separated arguments which are going to be grouped into the following option value, you could use getopt, or any other module then.
  • or do more fragile own processing:

    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)
    

这篇关于Python:有没有类似C的for循环可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆