【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 = ['apple','mango','banana','carrot']
>>> shoplist.append('meat')
>>> shoplist
['apple', 'mango', 'banana', 'carrot', 'meat']
2)向List中间指定索引位置插入一个对象:listname.insert(index,obj)
例:
shopList = ['apple','mango','banana','carrot']
>>> shoplist.insert(3,'rice')
>>> shoplist
['apple', 'mango', 'banana', 'rice', 'carrot', 'meat']
3)向List中添加一个List中的多个对象,相当于两个List相加:listname.extend(listname2)
例:
shopList = ['apple','mango','banana','carrot']
>>> shoplist2=['todou','maizi']
>>> shoplist2.extend(shoplist)
>>> shoplist2
['todou', 'maizi', 'apple', 'mango', 'banana', 'rice', 'carrot', 'meat']

4)判断某个对象是否在List中:obj in listname
例:
shopList = ['apple','mango','banana','carrot']
>>> 'apple' in shoplist
True
 
5)在List中搜索对象:listname.index(obj)
注:如果List中存在多个相同obj,则返回的是首次出现的索引,如果List中不存在该对象会抛出异常,所以查找对象之前一定要先判断一下对象是否在List中,以免引起程序崩溃
例:
shopList = ['apple','mango','banana','carrot']
>>> shoplist.index('apple')
0
>>> shoplist.index('rice') 

7)删除List中的对象:listname.remove(obj)
注:如果List中存在多个相同obj,则删除的是首次出现的对象,如果List中不存在该对象则会抛出异常,所以在删除之前也要判断对象是否在List中
例:
>>> shoplist.remove('apple')
>>> shoplist
['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 ?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值