三、python内置容器
标签: python 容器
3.1 List
定义 访问 切片操作 嵌套 内置函数
>>> a = [1,'2', ["abc", 1],34]>>> print a[1, '2', ['abc', 1], 34]>>> for o in a:... print o #必须有tab空格,否则o未定义...12['abc', 1]34>>> a =[x for x in range(10)]>>> a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> dir(a)['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']>>> a.append(10)>>> print a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> b=[11,12,13]>>> a.append(b)>>> a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, [11, 12, 13]]>>> a.extend(b)>>> print a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, [11, 12, 13], 11, 12, 13]
3.2 Tuple
定义 类似list的访问方式 不可变对象 隐式tuple调用
数据交换 拆封与解封
>>> a=(1,2,3)>>> type(a)<type 'tuple'>>>> print a(1, 2, 3)>>> dir(a)['__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']>>> for o in a:... print o...123>>> b = [x for x in a]>>> print b[1, 2, 3]>>> b=(x for x in a)>>> b<generator object <genexpr> at 0x7f36f045a870>>>> b.next()1>>> a[1]2>>> a[1:2](2,)>>> a[:-1](1, 2)>>> print 'abcd %d and %s\n' %(1,'ssss') #格式化串abcd 1 and ssss>>> a(1, 2, 3)>>> b = [x for x in a] #将a元组转化成数组来操作>>> print b[1, 2, 3]>>> b.append(4)>>> b[1, 2, 3, 4]>>> print b>>> a = (1,[1,2,3],4)>>> a(1, [1, 2, 3], 4)>>> type(a)<type 'tuple'>>>> a[2]=2Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment>>> a[1].append(2) #对元组中的数组进行增加操作>>> a(1, [1, 2, 3, 2], 4)
3.3 Dict
字典的声明 简单的使用 keys()和values() 排序问题
>>> a= {"b":1, "d":2}>>> a{'b': 1, 'd': 2}>>> type(a)<type 'dict'>>>> dir(a)['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']>>> if a.has_key('b'):... print a['b']...1>>> a.has_key('c')False>>> for o in a.iteritems():... print o...('b', 1)('d', 2)>>> for o in a.iteritems():... print o[1] #取a的value值...12>>> b=[x for x in a.iterkeys()]>>> b['b', 'd']>>> type(a.itervalues)<type 'builtin_function_or_method'>>>> c = [x for x in a.itervalues()]>>> c[1, 2]>>> a.values()[1, 2]>>> a ={"d":3, "b":2, "c":1 }>>> help(sorted)>>> e=sorted(a, key=lambda t:t[0]) #按key值排序>>> e['b', 'c', 'd']>>> a{'c': 1, 'b': 2, 'd': 3}
3.4 Set
定义方式 set唯一集合 合并功能 类型转换
>>> a=[1,2,3,4,4,5,5];>>> b=set(a)>>> bset([1, 2, 3, 4, 5])
3.5 map, reduce, filter
- map
>>> a=[1,2,3,4,5]>>> map(lambda x:x*2, a)[2, 4, 6, 8, 10]>>> map(lambda x:x^2, a) #异或操作[3, 0, 1, 6, 7]>>> map(lambda x:x*x, a)[1, 4, 9, 16, 25]
- reduce 归并
>>> reduce(lambda x,y: x+y, a)15>>> reduce(lambda x,y: x, a)1>>> reduce(lambda x: x*2, a) #无法实现归并Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: <lambda>() takes exactly 1 argument (2 given)>>> reduce(lambda x,y: x*y, a)120
- filter
>>> filter(lambda x:x%2, a)[1, 3, 5]>>> filter(lambda x:x%2+1, a)[1, 2, 3, 4, 5]>>> filter(lambda x:not x%2, a)[2, 4]
3.6 迭代器与生成器,协同和半协同
>>> import os>>> b = os.walk('.')>>> print [o for o in b] #打印所有的环境变量>>> b.next() #空Traceback (most recent call last):File "<stdin>", line 1, in <module>StopIteration>>> b=os.walk('.')>>> b.next() #逐个弹出>>> type(b)<type 'generator'>>>> def fab(m):... a,b=1,1... while(a<m):... yield a... a,b = b,a+b...>>> b = fab(b)>>> b.next()1>>> b.next()1>>> b.next()2>>> b.next()3
1189

被折叠的 条评论
为什么被折叠?



