列表:可修改
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]