python 没有引用,不能直接用 = copy(这样是copy reference)
所以需要深拷贝 b = a[:]
列表和元组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
a=[1,2,3,4,5] print "----------- index and slice ----------"
print a[0] print a[-1] print a[0:4] print a[0:5:2]
print "------------ ref and copy -----------"
a_ref=a
a[2]=100
print "a="+str(a) print "a_ref="+str(a_ref)
a_copy = a[:] print "a_copy="+str(a_copy) print "------------ list methods ----------" a.append(300) print "After append: a="+str(a)
a.insert(1,50) print "After insert: a="+str(a)
a.pop() print "After pop: a="+str(a)
a.sort() print "After sort: a="+str(a)
a.reverse() print "After reverse: a="+str(a)
a.count(num)
del a[0] print "After del: a="+str(a)
print "------------ ref and copy ------------" print "a="+str(a) print "a_ref="+str(a_ref) print "a_copy="+str(a_copy)
b=[a,a_ref,a_copy] c=[1,[1,2,3],'abc']
|
字典
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
name_age=(('xiaoli',33),('xiaowang',20),('xiaozhang',40)) a=dict(name_age) b=dict(xiaoli=33,xiaowang=20,xiaozhang=40)
text = 'c++ python shell ruby java javascript c' code_num = [38599, 100931, 26153, 93142, 84275, 184220, 46843]
text_list=text.split(' ') code_dict = dict(zip(text_list,code_num))
code_dict['python'] code_dict.keys() code_dict.values() code_dict.items()
a=code_dict.get('fortran',None)
a_ref = code_dict a_copy = code_dict.copy() or = copy.copy(code_dict) a_copy = copy.deepcopy(code_dict)
other_code = {'php':78014,'objective-c':34444} code_dict.update(other_code) del code_dict['c++'] a_ref a_copy a_ref.clear()
[(k,a_copy[k]) for k in sorted(a_copy.keys())] sorted(dict.iteritems(), key = lambda d:d[1], reverse = True)
|
列表解析
1 2
| [expr for iter_var in iterable] [expr for iter_var in iterable if cond_expr]
|