列表数据类型-列表常用操作
2015-08-23 23:07
656 查看
1.1通过列表推导构建列表
thelist = [1,10,3]thenewlist = [x+10 for x in thelist] #使用列表推导生成新的序列,[11, 20, 13]
thelist[:] = [x+10 for x in thelist] #使用列表推导直接对原列表进行=修改,[11, 20, 13]
print “thelist = “,thelist
print “thenewlist = “,thenewlist
print id(thelist) == id(thenewlist)
1.2返回列表中的有效索引范围
def list_get(L,i,v = None):if -len(L) <= i < len(L): #注意是小于len(L),不是小于等于
return L[i]
else:
return v
1.3循环访问序列中的元素和索引
seq = [1,3,’hello’,[1,’3’],{‘name’:”zl”}]for index,item in enumerate(seq):
print “index = “,index
print “item=”,item
1.4创建多维度的列表
multilist = [[col*row for col in range(5)] for row in [1,2,3,4,5,6,7,8,9,10]] #row in [1,2,3,4,5,6,7,8,9,10]为外层循环,[col*row for col in range(5)]为内存循环
print multilist1.5展开嵌套的列表
def list_or_tuple(x):return isinstance(x,(list,tuple))
def flatten(sequence,to_expand=list_or_tuple):
for item in sequence:
if to_expand(item):
for subitem in flatten(item,to_expand):
yield subitem
else:
yield item
seq2 = [1,2,[3,[],4,[5,6],7,[8,],],9]
for x in flatten(seq2):
print x
#
输出结果:
[]
[5, 6]
[8]
[3, [], 4, [5, 6], 7, [8]]
#1.6行列表中对列进行删除
listOfRows = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]newList = [[row[0],row[1],row[3]] for row in listOfRows]
print newList
1.7二维列表行列互换
arr= [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]print [[r[col] for r in arr] for col in range(len(arr[0]))]
print map(list,zip(*arr)) #法2
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法