|
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165 |
1、if语句的格式 if
test1: statement1 elif
test2: statement2 else statement32、在python中没有switch/case语句,可以通过字典或者if,elif,else模拟 例如: choice =
‘ham‘ print({‘spam‘:1.25,‘ham‘:1.99,‘eggs‘:0.99,‘bacon‘:1.10}[choice]) 或者: if
choice ==
‘spam‘: print(1.25) elif
choice ==
‘ham‘: print(1.99) elif
choice ==
‘eggs‘: print(0.99) elif
choice ==
‘bacon‘: print(1.10) else
: print(‘bad choice‘) 如果有默认处理情况,则通过字典的get方法 例如: branch =
{‘spam‘:1.25,‘ham‘:1.99,‘eggs‘:0.99,‘bacon‘:1.10} print(branch.get(‘spam‘,‘bad choice‘))3、跨越多行的方法:()|{}|[]或者\(不提倡使用)或者‘‘‘ ‘‘‘
""" """4、任何非零数字或者非空对象都为真,数字零,空对象,特殊对象,None都被认作是假,比较和相等测试会递归应用在数据结构中5、or操作,python会由左到右求算操作对象,返回第一个为真的对象,如果没有为真的对象,则返回最后一个对象。 print((2
or 3), (3
or 2)) #输出:2,3 print([] or
3) #输出:3 print([] or
{}) #输出:{}6、and操作,python会由左向右求算操作对象,当所有的为真时,返回右边那个对象,如果遇到为假的对象,则返回第一个为假的对象 print((2
and 3), (3
and 2)) #输出:3,2 print([] and
3) #输出:[] print([] and
{}) #输出:[]7、if/else三元表达式 if
x: a =
y else: a =
z 等价于: a =
y if
x else
z 等价于: a =
((x and
y) or
z) 等价于: a =
(‘z‘,‘y‘)[bool(x)]8、while循环,当没有执行break语句时,才执行else部分 while
test: statement1 else
statement29、在python中有一条空语句:pass
它什么也不做10、for循环 for
target in
object : statement else statement 例如: D =
{‘a‘:1,‘b‘:2,‘c‘:3} for
key in
D: print(key,‘=>‘,D[key]) for
(key,value) in
D.items(): print(key,‘=>‘,value) 11、range用法,range(终止),range(起始,终止),range(起始,终止,步长 )起始默认是0,步长默认是112、在python2.6中map也能实现zip函数功能,但是在python3.0中不能使用 例如: map(None,(‘a‘,b‘,‘c‘),(1,2,3)) #输出:[(‘a‘:1,‘b‘:2,‘c‘:3)]13、enumerate返回索引和该索引位置上所对应的值,该函数对字符串,列表,元组有效,对字典没有效 例如: s =
‘spam‘ for
(i,v) in
enumerate(s): print(i,‘->‘,v) print(‘*‘*8) L =
[‘a‘,‘b‘,‘c‘,‘d‘] for
(i,v) in
enumerate(L): print(i,‘->‘,v) print(‘*‘*8) t =
(‘a‘,‘b‘,‘c‘,‘d‘) for
(i,v) in
enumerate(t): print(i,‘->‘,v) print(‘*‘*8) |
原文:http://www.cnblogs.com/hbcb533/p/3673912.html