python列表学习2

list函数
append和extend
list.append(x),就是将某个元素x追加到已知的一个list后边。


>>> la
[1, 2, 3]
>>> lb
['qiwsir','python']
>>> la.extend(1b)
>>> la
[1, 2, 3, 'qiwsir', 'python']
>>> 1b
['qiwsir', 'python']




>>> la = [1,2,3]
>>> b = "abc"
>>> la.extend(b)
>>> la
[1, 2, 3, 'a', 'b', 'c']
>>> c = 5
>>> la.extend(c)
TypeError: 'int' object is not iterable


如果extend的对象是数值型,则报错。
extend 的对象是一个list,如果是str,则python会先把它按照字符为单位转化为list再追加到


已知list。


>>> la
[1, 2, 3, 'a', 'b', 'c']
>>> lb
['qiwsir', 'python']
>>> la[len(la):]=lb
>>> la
[1, 2, 3, 'a', 'b', 'c', 'qiwsir', 'python']
list.extend(L)等效于list[len(list):]=L,L是待并入的list






>>> astr = "python"
>>> hasattr(astr,'_iter_')
False
这里用内建函数hasattr()判断一个字符串是否是可迭代的,返回了False。


>>> astr = [1,2]
>>> hasattr(alst,'_iter_')
True
>>> hasattr(3,'_iter_')
False
hasattr()的判断本质就是看那个类型中是否有_iter_函数。




>>> new = [1,2,3]
>>> id(new)
3072383244L
>>> lst = ['python', 'qiwsir']
>>> id(lst)
3069501420L
用id()能够看到两个列表分表在内存中的“窝”的编号。


>>> lst.extend(new)
>>> lst
['python', 'qiwsir', 1, 2, 3]
>>> id(lst)
3069501420L
虽然lst经过extend()方法之后,扩容了,但是,内存中的地址没有变。


列表的一个重要特征:列表是可以修改的。这种修改,不是复制一个新的,而是在原地进行修改





列表扩容的函数append()和extend(),他们有相同的地方:
都是原地修改列表
既然是原地修改,就不返回值


原地修改没有返回值,就不能赋值给某个变量。
>>> one = ["good","good","study"]
>>> another = one.extend(["day","day","up"])#对于没有提供返回值的函数,
>>> another#结果是:这样的,什么也没有得到。
>>> one
["good","good","study","day","day","up"]




两者的不同点
>>> lst = [1,2,3]
>>> lst.append(["qiwsir","github"])
>>> lst
[1, 2, 3, ["qiwsir","github"]]
>>> len(lst)
4




>>> lst2 = [1,2,3]
>>> lst2.extend(["qiwsir","github"])
>>> lst2
[1, 2, 3, 'qiwsir', 'github']
>>> len(lst2)
5
appen是整建制地追加,extend是个体化扩编。






count
list.count(x)
Return the number of times x appears in the list.


>>> la = [1,2,1,1,3]
>>> la.count(1)
3
>>> la.append('a')
>>> la.append('a')
>>> la
[1, 2, 1, 1, 3, 'a', 'a']
>>> la.count('a')
2
>>> la.count(2)
1
>>> la.count(5)#:la中没有5,但是如果用这种方法找,不报错,返回的数字0
0




index
list.index(x)
Return the index in the list of the first item whose value is x.It is an error if 


there is no such item.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值