1.1.6 Python中list列表

list类型,也是Python的一种对象类型,翻译为:列表。
>>> a=[] #定义了一个空的列表,变量a相当于一个贴在其上的标签
>>> type(a)
<type 'list'>
>>> a=["1","3","hello"]
>>> a[0]
'1'
reversed() 列表反转
>>> a=["1","3","hello"]
>>> b=[1,2,3,4,5,6]
>>> list(reversed(b))
[6, 5, 4, 3, 2, 1]
>>> list(reversed(a))
['hello', '3', '1']
list.append(x) 往list末尾追加元素
>>> a.append("like")
>>> a
['1', '3', 'hello', 'like']
1.append和extend
append:
>>> a=[1,2,3]
>>> b=["hello","world"]
>>> a.append(b)
>>> a
[1, 2, 3, ['hello', 'world']]
>>> c=[1,2]
>>> c.append(3)
>>> c
[1, 2, 3]
extend:
>>> a=[1,2,3]
>>> b=["hello","world"]
>>> a.extend(b)
>>> a
[1, 2, 3, 'hello', 'world']
注意看下面例子:
>>> c=5
>>> a.extend(c)

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
a.extend(c)
TypeError: 'int' object is not iterable
>>> c="aaa"
>>> a.extend(c)
>>> a
[1, 2, 3, 'hello', 'world', 'a', 'a', 'a']
可以看出来如果extend的对象是数值型,则报错。所以,extend的对象是一个list,如果是str,则Python会先把它按照字符为单位转化为list再追加到已知list。
概括起来,extend函数也是将另外的元素增加到一个已知列表中,元素必须是iterable(迭代器)
2,count()
count的作用是数一数某个元素在该list中出现多少次,也就是某个
元素有多少个
>>> c=[1,2,3,1,1,4]
>>> c.count(1)
3
>>> c.append('a')
>>> c.append('a')
>>> c
[1, 2, 3, 1, 1, 4, 'a', 'a']
>>> c.count('a')
2
3,insert
除了向列表中追加元素,在现实中,还应该有“插入”。Python提供了这样的操作,list.insert(i,x)就是向列表插入元素的函数。
>>> a=[1,2,3]
>>> a.insert(0,"python")
>>> a
['python', 1, 2, 3]
>>> a.insert(2,"hello")
>>> a
['python', 1, 'hello', 2, 3]
list.insert(i,x)中的i是将元素x插入到列表中的位置,即将x插入到索引值是i的元素前面。注意,索引是从0开始的。
如果遇到那个i已经超过了最大索引值,会自动将所要插入的元素放到列表的尾部,即追加。
4,pop和remove
对列表,不仅能增加元素,还能被删除之。删除元素的方法有两个,它们分别是:
list.remove(x)
>>> a
['python', 1, 2, 3]
>>> a.insert(2,"hello")
>>> a
['python', 1, 'hello', 2, 3]
>>> a.remove(1)
>>> a
['python', 'hello', 2, 3]
>>> a.remove("hello")
>>> a
['python', 2, 3]
>>> a.append("python")
>>> a
['python', 2, 3, 'python']
>>> a.remove("python") #只删除第一个
>>> a
[2, 3, 'python']
注意:当remove删除的时候,没有删除的字符,会报错;删除之前应该 str in list 判断一下
list.pop([i]) 圆括号里面是[i],表示这个序号是可选的
>>> a
[2, 3, 'python']
>>> a.pop() #默认删除最后一个,并且将该结果返回
'python'
>>> a
[2, 3]
>>> a.append(1)
>>> a.append("hello")
>>> a
[2, 3, 1, 'hello']
>>> a.pop(1) #指定删除编号为1的元素
3
>>> a
[2, 1, 'hello']

下面还有结果常用的:
reverse比较简单,就是把列表的元素顺序反过来
>>> a
[2, 1, 'hello']
>>> a.reverse()
>>> a
['hello', 1, 2]
sort是对列表进行排序,也是让列表进行原地修改,没有返回值
>>> b=[4,2,1,7]
>>> b.sort()
>>> b
[1, 2, 4, 7]
>>> b.sort(reverse=True) #倒排序
>>> b
[7, 4, 2, 1]
>>> a=["hello","world","zhangsan","lisi"]
>>> a.sort(key=len) #以字符串的长度进行排序
>>> a
['lisi', 'hello', 'world', 'zhangsan']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值