Python:是否有类似 C 的 for 循环可用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3354313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:37:19  来源:igfitidea点击:

Python: is there a C-like for loop available?

pythonfor-loop

提问by Cristian Diaconescu

Can I do something like this in Python?

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

我想手动(即没有 getopt)解析一些 cmd 行参数,其中每个“关键字”都有一定数量的参数,如下所示:

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

    ...

采纳答案by SilentGhost

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

回答by sberry

Yes, this is how I would do it

是的,这就是我要做的

>>> for i in xrange(0, 10):
...     if i == 4:
...         continue
...     print i,
...
0 1 2 3 5 6 7 8 9

EDIT
Based on the update to your original question... I would suggest you take a look at optparse

编辑
基于对原始问题的更新......我建议你看看optparse

回答by kennytm

You should use continueto skip a value, in both C and Python.

continue在 C 和 Python 中,您应该使用跳过一个值。

for i in range(10):
  if someCondition:
     continue
  print(i)

回答by Charles Beattie

Strange way:

奇怪的方法:

for x in (x for x in xrange(10) if someCondition):
    print str(x)

回答by Christian Oudard

You probably don't actually need the indices, you probably need the actual items. A better solution would probably be like this:

您可能实际上并不需要索引,您可能需要实际的项目。更好的解决方案可能是这样的:

sequence = 'whatever'
for item in sequence:
    if some_condition:
        continue
    do_stuff_with(item)

回答by Teodor Pripoae

 for i in xrange(0, 10):
    if i % 3 == 0
        continue
    print i

Will only values which aren't divisible by 3.

只会被 3 整除的值。

回答by catchmeifyoutry

If you need to iterate over something, andneed an index, use enumerate()

如果您需要迭代某些内容需要索引,请使用enumerate()

for i, arg in enumerate(argv):
    ...

which does the same as the questioner's

与提问者的功能相同

for i in range(0,len(argv)):
    arg = argv[i]

回答by Tony Veijalainen

Your problem seems to be that you should loop not raw parameters but parsed parameters. I would suggest you to consider to change your decision not to use standard module (like the others).

您的问题似乎是您不应该循环原始参数,而是循环解析参数。我建议您考虑改变不使用标准模块的决定(像其他模块一样)。

回答by Larry

You could first turn the argv list into a generator:

你可以先把 argv 列表变成一个生成器:

def g(my_list):
    for item in my_list:
        yield item

You could then step through the items, invoking the generator as required:

然后,您可以单步执行这些项目,根据需要调用生成器:

my_gen = g(sys.argv[1:]):
while True:
   try:
      arg = my_gen.next()
      if arg == "--flag1":
         optX = my_gen.next()
         opyY = my_gen.next()
         --do something
      elif arg == "--flag2":
         optX = my_gen.next()
         optY = my_gen.next()
         optZ = my_gen.next()
         --do something else
      ...
    except StopIteration:
       break

回答by Netzsooc

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

In python would be written as

在python中会写成

i = 0
while i < 10
   if someCondition
      i += 1
   print i
   i += 1

there you go, that is how to write a c for loop in python.

好了,这就是如何在 python 中编写 ac for 循环。