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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值