【问题标题】:python 2.7 for loop repeat iterationpython 2.7 for循环重复迭代
【发布时间】:2014-05-13 20:52:47
【问题描述】:

首先,我想说对不起,因为我的英语不够好,但希望你能理解我。 我搜索了互联网,但找不到如何在 python 2.7 中执行此操作,我知道可以使用 while 循环来完成,但我想知道是否也可以使用 for。

如果我们有一个看起来像这样的 for 循环

for counter in range(0,len(list)):
    if (condition):
        var=something from dictionary

如果此条件为真,我需要重复相同的循环迭代。尝试使用i=i-1 但这不起作用,后来我发现python 在循环开始时创建了一个数字列表,也尝试了xrange 但没有奏效。那么,有谁知道如何做到这一点?

【问题讨论】:

  • for 循环中放置一个while condition

标签: python python-2.7


【解决方案1】:

您需要的是一个while 循环。您可以更轻松地控制循环内的迭代。你可以这样组织它:

i = 0
while i < len(list):
    if condition:
        var = something from dictionary
    else:
        i++

【讨论】:

  • 实际上是这样的,但是在c中可以使用for和重复迭代所以想知道这是否也可以在python中完成
  • 从 python 文档中阅读此内容,了解 python 中的 for 循环与其对应的 C 循环之间的区别。 docs.python.org/2/tutorial/controlflow.html
【解决方案2】:

你试过了吗

for l in list:
    if(condition):
        var=getValue()

有关更多示例详细信息,您可能会在 Python ForLoop 找到一个很好的示例

【讨论】:

  • 下推自动机需要这个,所以这不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-16
相关资源
最近更新 更多