簡體   English   中英

Python,循環循環的下一次迭代

[英]Python, next iteration of the loop over a loop

給定特定條件時,我需要得到第一個循環的下一個項,但條件是在內循環中。 有沒有比這更短的方法呢? (測試代碼)

    ok = 0
    for x in range(0,10):
        if ok == 1:
            ok = 0
            continue
        for y in range(0,20): 
            if y == 5:
                ok = 1
                continue

在這種情況下怎么樣?

for attribute in object1.__dict__:
    object2 = self.getobject()
    if object2 is not None:
        for attribute2 in object2: 
            if attribute1 == attribute2:
                # Do something
                #Need the next item of the outer loop

第二個例子顯示了我目前的情況。 我不想發布原始代碼,因為它是西班牙語。 object1和object2是兩個非常不同的對象,一個是對象關系映射的性質,另一個是webcontrol。 但是它們中的2個屬性在某些情況下具有相同的值,我需要跳轉到外循環的下一個項目。

break替換內循環中的continue 你想要做的是實際上打破內循環,所以continue那樣做你想要的相反。

ok = 0
for x in range(0,10):
    print "x=",x
    if ok == 1:
        ok = 0
        continue
    for y in range(0,20): 
        print "y=",y
        if y == 5:
            ok = 1
            break

您始終可以轉換為while循環:

flag = False
for x in range(0, 10):
    if x == 4: 
        flag = True
        continue

x = 0
while (x != 4) and x < 10:
    x += 1
flag = x < 10

沒有必要更簡單,但更好的imho。

您的示例代碼等同於(看起來不像您想要的):

for x in range(0, 10, 2):
    for y in range(20): 
        if y == 5:
           continue

要在外部循環中不使用continue而跳到下一個項目:

it = iter(range(10))
for x in it:
    for y in range(20):
        if y == 5:
           nextx = next(it)
           continue

所以你不是在追求這樣的事情嗎? 我假設你正在通過鍵來循環到字典,而不是你的例子中的值。

for i in range(len(object1.__dict__)):
  attribute1 = objects1.__dict__.keys()[i]
  object2 = self.getobject() # Huh?
  if object2 is not None:
    for j in range(len(object2.__dict__)):
      if attribute1 == object2.__dict__.keys()[j]:
        try:
          nextattribute1 = object1.__dict__.keys()[i+1]
        except IndexError:
          print "Ran out of attributes in object1"
          raise

我不清楚你想要什么,但是如果你正在為內循環中產生的每個項目測試一些東西,那么any你想要的東西都可以( docs

>>> def f(n):  return n % 2
... 
>>> for x in range(10):
...     print 'x=', x
...     if f(x):
...         if any([y == 8 for y in range(x+2,10)]):
...             print 'yes'
... 
x= 0
x= 1
yes
x= 2
x= 3
yes
x= 4
x= 5
yes
x= 6
x= 7
x= 8
x= 9

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM