列表:可修改
a=[1,2,3]
b=[4,5,6]
a+b==[1,2,3,4,5,6]
a*2==[1,2,3,1,2,3]
list('list')==['l','i','s','t']
排序
>>> x=[4,6,2,1,7,9]
>>> x.sort() # 沒有返回值
>>> x
[1, 2, 4, 6, 7, 9]
>>> y=[4,6,2,1,7,9]
>>> z=sorted(y) # 只有返回值
>>> z
[1, 2, 4, 6, 7, 9]
元組:不可修改
>>> 1,2,3
(1, 2, 3)
>>> (1,2,3)
(1, 2, 3)
>>> (1,) #必須有逗號
(1,)
>>> (1)
1
字典
>>> items=[('name','Gumy'),('age',16)]
>>> d = dict(items)
>>> d
{'age': 16, 'name': 'Gumy'}
>>> e = dict(name='yc', age=16)
>>> e
{'age': 16, 'name': 'yc'}
people = {
'yc01':{
'tele':123,
'add':'a1b2'
},#逗號
'yc02':{
'tele':312,
'add':'a2b2'
}
}
people['yc01']['add'] #字符串
if
if a>0:
print 'a>0'
elif a<0:
print 'a<0'
else:
print 'a=0'
is 同一性運算符
>>> x=y=[1,2,3]
>>> x is y
True
>>> x.append(4)
>>> x
[1, 2, 3, 4]
>>> y
[1, 2, 3, 4]
當爲同一時,一個修改另外一個也會修改
>>> a=[1,2,3]
>>> b=a[:]
>>> b.append(4)
>>> a
[1, 2, 3]
>>> b
[1, 2, 3, 4]
複製整個切片,完全不同的2個
while
while x<=3:
print x
x += 1
for
while x<=3:
print x
x += 1
>>> numbers = [1,2,3,4]
>>> for number in numbers:
print number
1
2
3
4
>>> for number in range(0,3):#下限爲0,上限爲3(包括下限,不包括上限)可以沒有下限(默認從0開始)第3個參數爲步長默認爲1
print number
0
1
2
列表推導式
>>> [x*x for x in range(3)]
[0, 1, 4]
>>> [x*x for x in range(10) if x % 3==0]
[0, 9, 36, 81]