Python学习笔记 第二课 循环

 >>> movies=["The Holy Grail", 1975, "The Life of Brian", 1979, "The Meaning of Life", 1983]
>>> for eachMovie in movies:
print(eachMovie)

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

 The Holy Grail
1975
The Life of Brian
1979
The Meaning of Life
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 函数名(参数):

  函数代码组
 >>> def print_lol(movies):
for each_item in movies:
if isinstance(each_item,list):
print_lol(each_item)
else:
print(each_item)

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

引用函数:

>>> print_lol (movies)

结果如下:

 The Holy Grail
1975
Terry Jones & Terry Gilliam
91
Graham Chapman
Michael Palin
John Cleese
Terry Gilliam
Eric Idle
Terry Jones

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

定义一个列表:

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

调用函数:

>>> print_lol(hello)

结果如下:

 a
b
1
3
hello
22
33
ok
h
zhuangshi

再看这个函数:

 >>> def print_lol(movies):
for each_item in movies:
if isinstance(each_item,list):
print_lol(each_item)
else:
print(each_item)

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

--End--

上一篇:Python学习_05_条件、循环


下一篇:python 学习笔记3(循环方式;list初始化;循环对象/生成器/表推导;函数对象;异常处理)