初学Python--列表(List)

1.索引

列表中的元素类型未必统一,如:

listExample=[1,2,'a','b']

元素下标索引以0开始

firstEle=listExample[0]

不能进行越界索引,但可以倒序索引

lastEle=listExample[-1]

但是取子List时可以进行下标越界如:

subList=listExample[-10,10]

不支持逆序取子List,如

subInvList1=listExample[-1,-2]
subInvList2=listExample[2,0]

但可以,即第一个下标要小于第二个下标,否则子列表为空

subInvList3=listExample[-2,-1]

2.List作为对象,Python提供了如下方法:append,clear,copy,count,extend,index,insert,pop,remove,reverse,sort

但同时又提供了len,del函数,现在来一个个看看吧

2.1.追加元素有append,insert,extend,很显然append和insert增加元素,只不过append是追尾,而insert可以对任意位置插入元素。而extend是在尾部将另一List扩展进来。而+虽然也能合并两个List,不过运算的结果作为新的List,对第一个List没有影响。

listExample.append('c')
listExample.insert(-1,'e')
listExample.extend(['f','g'])
listExample+['f','g']

2.2.pop,remove,del移除删除元素

pop将最后一个元素弹出,返回值为最后一个元素。而remove是将某个元素值移掉,移掉第一个出现的元素的值。del是删除指定下标的元素,del不是对象中的方法而是函数,也可以删除子列。

listExample.pop()
listExample.append('a')
listExample.remove('a')
del listExample[-1]
del listExample[-2:-1]

2.3.index,count统计某个元素

index返回元素的最小下标,而count则给出元素在List中出现的次数

listExample.index('b')
listExample.count('b')

2.4.copy,clear,sort,len

copy生成副本,但是对副本的操作不影响原有List。clear清空List元素,而sort就是按规则排序。至于len,这个不是List对象方法,可以统计List元素长度的函数

copyList=listExample.copy()
copyList.pop()
print(listExample)


copyList.clear()
print(copyList)

copyList.append(1)
copyList.append(2)
copyList.sort(key=None,reverse=False)

len(copyList)

3.小结

Python作为脚本语言没有像C/C++、Java繁琐,操作非常简洁、容易上手。从List操作可以看出Python支持面向对象提供了像pop()、remove()等方法,但是又提供了一些像len,del函数。

posted on 2014-03-06 17:47  i_bugs  阅读(1424)  评论(0编辑  收藏  举报

导航