用于增量内环的python

2024-05-20 21:00:35 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从内环递增外部迭代器?

更准确地说:

  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

上面是我想要实现的简单的想法。

这是我的Java代码:

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;

Tags: 代码inforifrangejavalengthint
3条回答

在python中,for循环在iterable上迭代,而不是递增一个计数器,因此您有两个选择。使用像Artsiom推荐的跳过标志是一种方法。另一个选择是从您的范围生成一个生成器,并通过使用next()丢弃一个元素来手动推进它。

iGen = (i for i in range(0, 6))
for i in iGen:
    print i
    if not i % 2:
        iGen.next()

但这还不完全,因为next()如果到达范围的末尾,可能会抛出一个stopietition,因此必须添加一些逻辑来检测它,如果发生这种情况,则必须从外部循环中断。

最后,我可能会使用aw4ully的while循环的解决方案。

使用while循环比使用for循环更好。我直接从java代码中翻译了您的代码。

str1 = "ababa"
str2 = "aba"
i = 0

while i < len(str1):
  j = 0
  while j < len(str2):
    if not str1[i+j] == str1[j]:
      break
    if j == (len(str2) -1):
      i += len(str2)
    j+=1  
  i+=1

似乎您要使用范围函数的步长参数。来自文档:

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],可以使用:

range(0,6,2)

或者在您的情况下,什么时候是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

相关问题 更多 >