# -*- coding: utf-8 -*- # 一 元组 # 1 定义 tup1 = () # 空 tup2 = (0, ) # 注意,必须有分号 tup3 = (1, 2, 3, 4) # 2 操作 # 2.1 合并 tup4 = tup2 + tup3 # (0, 1, 2, 3, 4) # 2.2 长度 print len(tup4) # 5 # 2.3 切片 print tup4[0:4:2] # (0, 2) # 3 遍历 for val in tup4: print val ''' 0 1 2 3 4 ''' for i in range(len(tup4)): print i, tup4[i] ''' 0 0 1 1 2 2 3 3 4 4 ''' # 二 列表 # 1 定义 list1 = [] # 空 list2 = [0] list3 = [1, 2, 3, 4] # 2 操作 # 2.1 合并 list4 = list2 + list3 # [0, 1, 2, 3, 4] # 2.2 长度 print len(list4) # 5 # 2.3 切片 print list4[0:4:2] # [0, 2] # 2.4 追加 list2.append(5) # [0, 5] # 2.5 移出 list2.pop(0) # [5], 不指定下标默认移出最后一项 # 3 遍历 for val in list4: print val ''' 0 1 2 3 4 ''' for i in range(len(list4)): print i, list4[i] ''' 0 0 1 1 2 2 3 3 4 4 ''' for i, item in enumerate(list4): print i , item ''' 0 0 1 1 2 2 3 3 4 4 ''' # 三 字典 # 1 定义 dic1 = {} # 空 dic2 = {'one': 1} dic3 = {'two': 2} # 2 操作 # 2.1 合并 dic3.update(dic2) # {'one': 1, 'two': 2} # 或者 # dic3 = dict(dic3, **dic2) # 2.2 长度 print len(dic3) # 3 # 2.3 keys print dic3.keys() # ['one', 'two'] # 2.4 values print dic3.values() #[1, 2] # 2.3 items print dic3.items() # [('one', 1), ('two', 2)] # 2.4 in print 'one' in dic3 # True print 1 in dic3 # False # 2.5 pop dic3.pop('one') # {'two': 2} # 3 遍历 for val in dic3: # for val in dic3.iterkeys(): print val ''' one two ''' for val in dic3.itervalues(): print val ''' 1 2 ''' for val in dic3.iteritems(): print val ''' ('one', 1) ('two', 2) ''' for key, val in dic3.iteritems(): print key, val ''' one 1 two 2 ''' # 四 集合 # 1 定义 set1 = set() set2 = set([0,1]) #set([0, 1]) print set2 # 2 操作 # 2.1 长度 print len(set2) # 2 # 2.2 添加 set2.add(2) # 一项 ([0, 1, 2]) set2.update([3, 4]) # 多项 ([0, 1, 2, 3, 4]) # 2.3 移出 set2.remove(4) # ([0, 1, 2, 3]) # 2.4 集合运算 p1 = set([1, 2]) p2 = set([2, 3]) print p1 & p2 # 交集 ''' set([2]) ''' print p1 - p2 # 差集 ''' set([1]) ''' print p1 & p2 # 差集 ''' set([3]) ''' print p1 | p2 # 并集 ''' set([1, 2, 3]) ''' # 3 遍历 for val in set2: print val ''' 0 1 2 3 '''