python2(HBK) 基本数据结构

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
#!/usr/bin/env python
# coding: utf-8
#copyRight by heibanke

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] #从0开始到第五个元素 step = 2 == [1,3,5]

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) #a含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
#!/usr/bin/env python
# coding: utf-8
#copyRight by heibanke

#--------用dict直接生成,
name_age=(('xiaoli',33),('xiaowang',20),('xiaozhang',40))
a=dict(name_age)
b=dict(xiaoli=33,xiaowang=20,xiaozhang=40)

#--------如何将两个等长度的list合并成dict
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))# zip将两个list生成字典

#--------key, keys, items, values
code_dict['python']
code_dict.keys()
code_dict.values()
code_dict.items()

#--------get
a=code_dict.get('fortran',None)

#------- ref and copy
a_ref = code_dict
a_copy = code_dict.copy() or = copy.copy(code_dict)#浅拷贝
a_copy = copy.deepcopy(code_dict) #浅拷贝

#--------update, del, copy, clear
other_code = {'php':78014,'objective-c':34444}
code_dict.update(other_code)
del code_dict['c++']
a_ref
a_copy
a_ref.clear()

#--------sort key and value
[(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]
文章目录
  1. 1. 列表和元组
  2. 2. 字典
  3. 3. 列表解析