1,补充一点列表传参需要注意的地方:列表传参,是传引用
#!/usr/bin/python #coding:utf-8 def show( l ): print '函数里面' print id( l ) l[0] = 100 a = [ 10, 20, 30 ] print '调用前' print id( a ) print '调用后' show( a ) print a
执行结果:
ghostwu@ghostwu:~/python/tmp$ !p python list_arg.py 调用前 140000495519000 调用后 函数里面 140000495519000 [100, 20, 30]
2,我们可以在函数里面对传递的列表参数,做一个拷贝,就不会是传引用了
#!/usr/bin/python #coding:utf-8 def show( l ): b = l[:] print '函数里面' print id( b ) b[0] = 100 a = [ 10, 20, 30 ] print '调用前' print id( a ) print '调用后' show( a ) print a
执行后
ghostwu@ghostwu:~/python/tmp$ python list_arg2.py 调用前 140145018864920 调用后 函数里面 140145018776680 [10, 20, 30]
集合:没有顺序的概念,不能进行索引或者切片操作
1、创建集合. set():可变的 不可变的frozenset()
2,集合add与update操作
>>> a = set() >>> type( a ) <type 'set'> >>> a.add( 10 ) >>> a.add( 20 ) >>> a set([10, 20]) >>> a.add( 'ghostwu' ) >>> a set([10, 20, 'ghostwu']) >>> a.update( 'ghostwu' ) >>> a set(['g', 'h', 10, 'o', 's', 20, 't', 'w', 'u', 'ghostwu']) >>>
update操作,把自身一个个添加到集合
remove操作,删除一个不存在的元素会报错
>>> a set(['g', 'h', 10, 'o', 's', 20, 't', 'w', 'u', 'ghostwu']) >>> a.remove( 'ghostwu' ) >>> a set(['g', 'h', 10, 'o', 's', 20, 't', 'w', 'u']) >>> a.remove( 20 ) >>> a set(['g', 'h', 10, 'o', 's', 't', 'w', 'u']) >>> a.remove( 'ab' ) Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'ab' >>>
判断成员是否存在in, not in
>>> a set(['g', 'h', 10, 'o', 's', 't', 'w', 'u']) >>> 'g' in a True >>> 'h' not in a False >>> 10 in a True >>>
集合:交集,并集,差集
交集:
>>> a = set( 'abcd' ) >>> b = set( 'bcdef' ) >>> a & b set(['c', 'b', 'd']) >>>
并集:
>>> a | b set(['a', 'c', 'b', 'e', 'd', 'f']) >>>
差集:
>>> a - b set(['a']) >>> b - a set(['e', 'f']) >>>
去重复:
>>> l = [1,2,3] >>> l.append( 1 ) >>> l.append( 3 ) >>> l [1, 2, 3, 1, 3] >>> a = set( l ) >>> a set([1, 2, 3]) >>> type( a ) <type 'set'> >>> l [1, 2, 3, 1, 3] >>> l = list ( a ) >>> l [1, 2, 3] >>>
frozenset不能进行add,remove操作
>>> s = frozenset( 'abc' ) >>> s frozenset(['a', 'c', 'b']) >>> s.add( 'd' ) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'frozenset' object has no attribute 'add' >>> s.remove( 'a' ) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'frozenset' object has no attribute 'remove' >>>