用于增量内循环的python [英] python for increment inner loop

查看:62
本文介绍了用于增量内循环的python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从内循环增加外迭代器?

How to increment the outer iterator from the inner loop?

更准确地说:

  for i in range(0,6):
    print i
    for j in range(0,5):
      i = i+2

我要了

0
1
2
3
4
5

,但我想要 0,2,4

以上是我想要实现的简化想法.

Above is the simpilfied idea what I want to acheive.

这是我的 Java 代码:

Here is my Java code:

str1="ababa"
str2="aba"
for(int i =0; i < str1.length; i++)
  for(int j =0; j < str2.length; j++)
       if str1[i+j]!=str[j]
           break;
       if( j ==str2.length -1)
           i=i+str2.length;

推荐答案

看来要使用 range 函数的 step 参数.来自文档:

It seems that you want to use step parameter of range function. From documentation:

range(start, stop[, step]) 这是一个多功能的函数来创建包含算术级数的列表.它最常用于循环.参数必须是普通整数.如果 step 参数是省略,默认为 1.如果省略 start 参数,则默认为 0.完整形式返回一个纯整数列表 [start,开始 + 步,开始 + 2 * 步,...].如果 step 为正,则最后一个element 是最大的 start + i * step 小于 stop;如果步骤是负数,最后一个元素是最小的 start + i * step 更大比停止.step 不能为零(否则会引发 ValueError).示例:

range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:

 >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 >>> range(0, 30, 5) [0, 5, 10, 15, 20, 25]
 >>> range(0, 10, 3) [0, 3, 6, 9]
 >>> range(0, -10, -1) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
 >>> range(0) []
 >>> range(1, 0) []

在您获得 [0,2,4] 的情况下,您可以使用:

In your case to get [0,2,4] you can use:

range(0,6,2)

或者在你的情况下是 var:

OR in your case when is a var:

idx = None
for i in range(len(str1)):
    if idx and i < idx:
        continue
    for j in range(len(str2)):
        if str1[i+j] != str2[j]:
            break
    else:
        idx = i+j

这篇关于用于增量内循环的python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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