Python学习笔记:第一次接触

时间:2022-06-21 20:47:42

用的是windows的IDLE(python 3)

对象的认识:先创建一个list对象(用方括号)

1 a = ['xieziyang','chenmanru']
2 a

对list中对象的引用

1 a[0] # 表示列表a中的第一个对象

在列表的末尾添加一个对象

1 a.append('xiemanru')
2 a.insert(0,'xiemanru1') # 在指定位置插入一个对象insert object before index

移除对象

a.remove('xiemanru')
a

for循环:

1  movies = ['The Holy Grail','The Life of Brian','The Meaning of Life']
2  years = [1975,1979,1983]
3  k = 1
4  for time in years:
5            movies.insert(k,time)
6        k = k+2
7  movies

在列表中再插入一个列表:

1 movies.insert(2,['Transformer',2007]

引用:

>>> movies[2][0]
'Transformer'

嵌套列表的打印:

1 >>> for each_item in movies:
2     if isinstance(each_item,list):  # 判断each_item是否为列表
3         for nested_item in each_item:
4             print(nested_item)
5     else:
6         print(each_item)

对于多重嵌套列表的打印:再添加一个列表

1 >>> movies[2].insert(1,['阿甘正传',2010])
2 >>> movies
['The Holy Grail', 1975, ['Transformer', ['阿甘正传', 2010], 2007], 'The Life of Brian', 1979, 'The Meaning of Life', 1983]

定义函数:

1 def print_it_all(the_list):  # 定义一个函数:def 函数名(参数):函数代码组
2     for each_item in the_list:
3         if isinstance(each_item,list):
4             print_it_all(each_item)
5         else:
6             print(each_item)

看看效果:

 1 >>> print_it_all(movies)
 2 The Holy Grail
 3 1975
 4 Transformer
 5 阿甘正传
 6 2010
 7 2007
 8 The Life of Brian
 9 1979
10 The Meaning of Life
11 1983

改进一下,打印的更好看:

1 def print_it_all(the_list,level):
2     for each_item in the_list:
3         if isinstance(each_item,list):
4             print_it_all(each_item,level+1)
5         else:
6             for tab_stop in range(level):
7                 print("\t",end = '')
8             print(each_item)

看一下结果:

 1 print_it_all(movies,0)
 2 The Holy Grail
 3 1975
 4     Transformer
 5         阿甘正传
 6         2010
 7     2007
 8 The Life of Brian
 9 1979
10 The Meaning of Life
11 1983

再添加一个参数控制是否缩进打印:

1 def print_it_all(the_list,indent = False,level = 0):
2     for each_item in the_list:
3         if isinstance(each_item,list):
4             print_it_all(each_item,indent,level+1)
5         else:
6             if indent:
7                 for tab_stop in range(level):
8                     print("\t",end = '')
9             print(each_item)

看看结果怎么样:

 1 >>> print_it_all(movies)
 2 The Holy Grail
 3 1975
 4 Transformer
 5 阿甘正传
 6 2010
 7 2007
 8 The Life of Brian
 9 1979
10 The Meaning of Life
11 1983
12 >>> print_it_all(movies,indent = True)
13 The Holy Grail
14 1975
15     Transformer
16         阿甘正传
17         2010
18     2007
19 The Life of Brian
20 1979
21 The Meaning of Life
22 1983

 

看的书是head frist Python,挺适合初学者看的

以上代码也是参照上书内容,敲几遍就变成自己的了:)

欢迎大家来指教