Python学习笔记 第二课 循环

 1 >>> movies=["The Holy Grail", 1975, "The Life of Brian", 1979, "The Meaning of Life", 1983]

 2 >>> for eachMovie in movies:

 3     print(eachMovie)

按下两个回车后输出结果如下:

1 The Holy Grail

2 1975

3 The Life of Brian

4 1979

5 The Meaning of Life

6 1983

列表中还可以存储其他列表!

 

movies = ["The Holy Grail", 1975, "Terry Jones & Terry Gilliam", 91,

          ["Graham Chapman",

          ["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]
       ]
      ]

 

这样的嵌套列表用上面的for循环怎么处理呢?

>>> for each_item in movies:

    print(each_item)



    

The Holy Grail

1975

Terry Jones & Terry Gilliam

91

['Graham Chapman', ['Michael Palin', 'John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones']]

哦!没有处理干净......

再循环!

>>> for each_item in movies:

    if isinstance(each_item,list):

        for nested_item in each_item:

            if isinstance(nested_item,list):

                for deeper_item in nested_item:

                    if isinstance(deeper_item,list):

                        for deepest_item in deeper_item:

                            print(deepest_item)

                    else:

                        print(deeper_item)

            else:

                print(nested_item)

    else:

        print(each_item)



        

The Holy Grail

1975

Terry Jones & Terry Gilliam

91

Graham Chapman

Michael Palin

John Cleese

Terry Gilliam

Eric Idle

Terry Jones

哇塞!这倒是处理干净了,但是也太绕了吧!不过队形不错!

用函数来处理

def 函数名(参数):



  函数代码组
1 >>> def print_lol(movies):

2     for each_item in movies:

3         if isinstance(each_item,list):

4  print_lol(each_item) 5         else:

6             print(each_item)

6行代码即可完成上面的晕头转向。

引用函数:

>>> print_lol (movies)

结果如下:

 1 The Holy Grail

 2 1975

 3 Terry Jones & Terry Gilliam

 4 91

 5 Graham Chapman

 6 Michael Palin

 7 John Cleese

 8 Terry Gilliam

 9 Eric Idle

10 Terry Jones

我们以后就可以用这个函数来处理各种嵌套列表了。

定义一个列表:

>>> hello=["a","b",1,3,["hello",22,33,["ok","h"]],"zhuangshi"]

调用函数:

>>> print_lol(hello)

结果如下:

 1 a

 2 b

 3 1

 4 3

 5 hello

 6 22

 7 33

 8 ok

 9 h

10 zhuangshi

再看这个函数:

1 >>> def print_lol(movies):

2     for each_item in movies:

3         if isinstance(each_item,list):

4  print_lol(each_item)

5         else:

6             print(each_item)

在代码内部引用了自身!——递归!没错是递归。Python3默认递归深度不能超过100,但是这个深度上限可以改。

--End--

 

 

 

你可能感兴趣的:(python)