嵌套for循环中的Python索引

时间:2016-05-26 19:44:35

标签: python

我可以把它放在另一个例子中:

Import-Module ac*
# Student
Get-AdUser -Filter * -SearchBase "OU=Student, OU=PPS, DC=ad, DC=ppsnet" -Properties GivenName, Surname, EmployeeNumber, SamAccountName, PhysicalDeliveryOfficeName, department |

`Where {$_.department -like "*KG*" -and  $_.SamAccountName -cmatch '(?:[A-Z][a-z][A-Z].*3)'} | Select GivenName, Surname, EmployeeNumber, SamAccountName, PhysicalDeliveryOfficeName, department |

Export-csv .\Output\Student\Kinders.csv  -NoTypeInformation

返回

q=[[100,101,103,104],[201,202,204],[301,302,304],[401,402,403]]

for index, item in enumerate(q):
      for i,t in enumerate(q[index]):
          if q[index][i+1]-q[index][i]==2:
             print index, i, q[index][i]

它应该返回

0 1 101

似乎break语句打破了循环,因此它停在第一个列表中。

如果我通过

修改它
0 1 101
1 1 202
2 1 302

当然这很好,但我仍然想知道是否有一种不必减少索引的方法,因为最后一项也是有价值的。

2 个答案:

答案 0 :(得分:1)

要遍历列表列表,您可以使用以下代码:

p=[['a','b','c','d'],
   ['a','c','e','d'],
   ['a','b','z','x']]

for i,item in enumerate(p):
    for j,x in enumerate(item):
        print i,j,x

输出:

0 0 a
0 1 b
0 2 c
0 3 d
1 0 a
1 1 c
1 2 e
1 3 d
2 0 a
2 1 b
2 2 z
2 3 x

答案 1 :(得分:1)

for index,item in enumerate(p):
     print 'top', index     #The index is at this level
     for x in range(len(item)):
         print 'loop' ,index  # Not this level where you print it.