文章目录:
- python内置数据结构
- 切片
- list查找,排序
python内置数据结构:列表(list),元组(tuple),字典(dirt)
map
函数可以根据函数,返回相应的结果生成相应的列表。
list=[1,3,4,5,6,7,8]def a(x): return x**2 b=map(a,list); for i in b: print i
list.append(val) 添加到列表尾部。
list.remove(val) #一次只移除一个。 从头开始删除。
list.insert(index,val)
list.pop()
字典遍历:
dict = {'name':'xyt','age':18,'sex':'male'} for (x,y) in dict.items(): print "index: %s value: %s" % (x,y)
dict.items()
dict.iteritems()
dict.setdefault('job','php programer') # 增加新值。#如果存在,则返回该索引对应的值。
dict.get(index)
dict.pop(index)
dict.keys()
dict.values()
dict.values(DICT)
深拷贝,浅拷贝
#浅拷贝 import copy a = [1, 2, 3, 4, ['a', 'b']] #原始对象 b=copy.copy(a) b[1]=12 #b[1]是一个整型,所以不会拷贝复制。只会直接复制他的值。 b[4][1]='c' #对象不一样,共用同一个地址。 print [id(i) for i in a] print [id(i) for i in b] print [i for i in a] print [i for i in b]
output:
[154063024, 154063012, 154063000, 154062988, 3072470444L]
[154063024, 154062892, 154063000, 154062988, 3072470444L]
[1, 2, 3, 4, ['a', 'c']]
[1, 12, 3, 4, ['a', 'c']]
import copy a = [1, 2, 3, 4, ['a', 'b']] #原始对象 b=copy.deepcopy(a) b[1]=12 b[4][1]='c' print [id(i) for i in a] print [id(i) for i in b] print [i for i in a] print [i for i in b]
output:
[152920240, 152920228, 152920216, 152920204, 3072950348L]
[152920240, 152920108, 152920216, 152920204, 3073071948L]
[1, 2, 3, 4, ['a', 'b']]
[1, 12, 3, 4, ['a', 'c']]
#赋值 import copy a = [1, 2, 3, 4, ['a', 'b']] #原始对象 b=a b[1]=12 b[4][1]='c' print [id(i) for i in a] print [id(i) for i in b] print [i for i in a] print [i for i in b]
output:
[164077744, 164077612, 164077720, 164077708, 3072609708L]
[164077744, 164077612, 164077720, 164077708, 3072609708L]
[1, 12, 3, 4, ['a', 'c']]
[1, 12, 3, 4, ['a', 'c']]
切片:
list=[1,5,1,3,4,5,6,7,8] print list[0:-1] print list[0:7:2]
output:
[1, 5, 1, 3, 4, 5, 6, 7]
[1, 1, 4, 6]
查找,排序。
#查找 list=[1,5,1,3,4,5,6,7,8] print list.index(7, )
#排序 list=[1,5,1,3,4,5,6,7,8] list.sort() #reverse=True 类表降序排序。 print list