列表数据类型-列表常用操作

来源:互联网 发布:java中图片上传和回显 编辑:程序博客网 时间:2024/04/30 02:51

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 multilist

1.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

0 0