天天看点

【python】list 的用法

定义及初始化生成list对象

shoplist = []

或者

shoplist = ['apple','mango','banana','carrot']

从list中取出对象,类似其他开发语言中的数组用法用listname[index],代表从前开始取第index个对象(第一个从0开始记),不同的是多了一种用负数取对象listname[-index],代表从后开始取第index个对象(第一个从-1开始记)

>>> shoplist[0]

'apple'

>>> shoplist[-1]

'carrot'

其实负数 a取法可以换算为:listname[len(listname) + a]

从list中截取部分对象生成新list:listname[fromindex:toindex]代表取出索引从fromindex到toindex,但不包括toindex的元素,这个也叫做list的分片

shoplist[0:2]取出从0开始到第2个元素但不包括shoplist[2],所以结果就相当于取出了shoplist[0]和shoplist[1]组合成的新list

结果为['a','b']

‘:’两边的值可以省略,前面省略代表0,后面省略代表list长度

shoplist[0:2]相当于shoplist[:2]

>>> shoplist[2:]

['banana', 'carrot']

>>> shoplist[1:3] 

['mango', 'banana']

向list添加对象有3种方法

1)向list后面添加一个对象:listname.append(obj)

例:

>>> shoplist.append('meat')

>>> shoplist

['apple', 'mango', 'banana', 'carrot', 'meat']

2)向list中间指定索引位置插入一个对象:listname.insert(index,obj)

>>> shoplist.insert(3,'rice')

['apple', 'mango', 'banana', 'rice', 'carrot', 'meat']

3)向list中添加一个list中的多个对象,相当于两个list相加:listname.extend(listname2)

>>> shoplist2=['todou','maizi']

>>> shoplist2.extend(shoplist)

>>> shoplist2

['todou', 'maizi', 'apple', 'mango', 'banana', 'rice', 'carrot', 'meat']

4)判断某个对象是否在list中:obj in listname

>>> 'apple' in shoplist

true

5)在list中搜索对象:listname.index(obj)

注:如果list中存在多个相同obj,则返回的是首次出现的索引,如果list中不存在该对象会抛出异常,所以查找对象之前一定要先判断一下对象是否在list中,以免引起程序崩溃

>>> shoplist.index('apple')

>>> shoplist.index('rice') 

7)删除list中的对象:listname.remove(obj)

注:如果list中存在多个相同obj,则删除的是首次出现的对象,如果list中不存在该对象则会抛出异常,所以在删除之前也要判断对象是否在list中

>>> shoplist.remove('apple')

['mango', 'banana', 'rice', 'carrot']

对list进行运算

1)相加:listname1 + listname2 

注:结果为新生成一个list,并没有修改之前的两个list

>>> shoplist + shoplist2

['mango', 'banana', 'rice', 'carrot', 'meat', 'todou', 'maizi', 'apple', 'mango', 'banana', 'rice', 'carrot', 'meat', 'todou', 'maizi', 'apple', 'mango', 'banana', 'rice', 'carrot', 'meat']

2)倍数:listname*n

>>> shoplist * 2

['mango', 'banana', 'rice', 'carrot', 'mango', 'banana', 'rice', 'carrot']

注意:没有减法:

>>> shoplist - shoplist2

traceback (most recent call last):

  file "", line 1, in ?