python学习日记[2]
元组:(用())
和列表的不同:
1、 列表更加灵活,可以任意的添加删除元素,元组一旦被创建就不可更改;
>>> dir(test) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index'] >>> test[1:] (2, 3, 4) >>> test[:3] (1, 2, 3) >>> test[1:] (2, 3, 4) >>> test[:3] (1, 2, 3)
p.s.
1、 在列表和元素中元素的类型不做限定,可以嵌套,有点类似于锯齿数组
2、 切片
格式化操作string:
1、 类似于C语言中printf一类函数要求的格式化输入。
2、 格式控制符的转义。
序列:
1、list() -> new empty list
list(iterable) -> new list initialized from iterable's items
2、 zip()---zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表。
函数:
定义 def return_value function_name(parameters):
#函数实现
1、 函数嵌套---Python支持函数内嵌—函数内部定义函数;
2、 函数闭包---子函数可以使用父函数中的局部变量,这种行为就叫做闭包!
示例图解
3、拓展阅读
>>> def test1(*aaa): print(aaa) def test2(): print(aaa) >>> test1(1,2,3,4) (1, 2, 3, 4) >>> def test1(*aaa): print(aaa) def test2(): print(aaa) print('test2_function called') >>> test1(1,23,4) (1, 23, 4) >>> test2() Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> test2() NameError: name 'test2' is not defined >>> def test1(*aaa): print(aaa) def test2(): print(aaa) print('test2_function called') return aaa*2 return test2() >>> test1(1,2,3) (1, 2, 3) (1, 2, 3) test2_function called (1, 2, 3, 1, 2, 3)