0

我对 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,然后循环会意识到它位于子列表的末尾,我可以调用该子列表)。

非常感谢!

4

3 回答 3

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]
于 2013-08-27T15:10:02.897 回答
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
于 2013-08-27T15:23:51.633 回答
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)
于 2013-08-27T15:11:44.557 回答