2013-08-27 64 views
0

我對Python非常陌生,正在嘗試通過列表清單工作。在Python中使用列表清單

說我有:

myList = [[1,2,3,4],[10,11,12,13],[29,28,27,26]] 

和函數調用myFunction的

我可以這樣寫:

for x in myList: 
    for y in x: 
    myFunction(y) 

然而,這只是調用myFunction的在各個項目中的所有子列表。當我完成每個子列表中的所有項目時(例如,我會調用1,2,3和4,然後循環會意識到它在子列表的末尾,我可以如何結合我可以調用的東西調用該子列表)。

非常感謝!

回答

5

你在外環想要的東西:

>>> for x in myList: 
...  for y in x: 
...   print(y) 
...  print(x) # <--- 
... 
1 
2 
3 
4 
[1, 2, 3, 4] 
10 
11 
12 
13 
[10, 11, 12, 13] 
29 
28 
27 
26 
[29, 28, 27, 26] 
+0

謝謝!如果我想在外部循環中做什麼,只能在內部循環中的項目完成後才能完成?在這種情況下,我想要處理每個子列表的內部循環中的項目,然後調用子列表,然後繼續處理下一個子列表中的項目。 – John

+0

@John,在上面的代碼中,'p​​rint(x)'僅在內部循環完成後才執行。 – falsetru

0

希望這是你想要什麼:

def myFunction(y): 
    print y 

myList = [[1,2,3,4],[10,11,12,13],[29,28,27,26]] 

for x in range(len(myList)): 
    print "Sublist:",x, myList[x] 
    for y in myList[x]: 
    myFunction(y) 
1

John,它是Python, 縮進語法而它縮進它是一個代碼塊,也就是說所有的命令都在包中(在塊中):

for x in myList: 
    # block of code started 
    for y in x: 
     # here is new block 
     # some here will be called totally "all elements in all sublists" times 
     # i.e. "number of elements in x" times 
     # per "number of sublist in myList" times 
     # and here will be called the same number of times (it is block) 
    # here you're out of "for y in x" loop now (you're in previous block) 
    # some here will be called "myList" number of times 
    # and here 
# here you are out of "for x in myList" loop