前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python3学习之列表

python3学习之列表

作者头像
py3study
发布2020-01-03 16:31:46
3130
发布2020-01-03 16:31:46
举报
文章被收录于专栏:python3python3

列表:


L.append(object)   追加

备注:append将obj作为一个整体追加,无论obj是字符串、数字、字典、列表等,当是字典时全部插入,跟L.extend(iterable) 不同

test = [1,2,3,4,5]

test1 = [6,7,8,9]

test.append(test1) : [1, 2, 3, 4, [6, 7, 8, 9]]

test.append(10) : [1, 2, 3, 4,10]


L.copy()  复制

备注:没有参数,采用 test2 = test.copy()的方法获取新的列表,该列表在内存中被新建,有新id

test2 = test.copy()

In [25]: id(test2 )

Out[25]: 140016313353992

In [26]: id(test)

Out[26]: 140016297719112


L.extend(iterable)  扩展(注意跟追加的区别)

备注:iterable 可以是列表、元组、字典。它将iterable中的元素追加到L中,当是字典时只追加item,没有追加value

In [43]: test=[1,2,3]

In [45]: test.extend([4,5,6])

In [46]: print(test)

[1, 2, 3, 4, 5, 6]

In [47]: test.extend((7,8))

In [48]: print(test)

[1, 2, 3, 4, 5, 6, 7, 8]

In [49]: test.extend({9:'aaa',10:'bbb'})

In [50]: print(test)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


L.insert(index, object)  插入

备注:在index前插入,index从0开始,obj作为一个整体,无论是列表、元组、字典等,当是字典时全部插入,跟L.extend(iterable) 不同

In [53]: print(test)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [54]: test.insert(3,'aaaa')

In [55]: print(test)

[1, 2, 3, 'aaaa', 4, 5, 6, 7, 8, 9, 10]

In [56]: test.insert(3,[1,2,3])

In [57]: print(test)

[1, 2, 3, [1, 2, 3], 'aaaa', 4, 5, 6, 7, 8, 9, 10]


L.pop([index])  弹出

L.remove(value) 移除

L.clear()   清空

备注:pop的参数是index,remove的参数是value,目的一样,clear是删除所有


L.sort(key=None,reverse=False) 排序

备注:默认是正序,即:1 2 3.... a b c...;reverse=True时是倒序,key参数一般不用,L中不可以包含嵌套列表、字典等


L.count(value)  计数

备注:返回值等于value出现的次数

L.index(value, [start, [stop]])  查找

备注:返回值是在指定的范围内第一次出现的等于value的index,stop=最大index+1才能判断到最后一个value

In [117]: print(tt)

[5, 4, 3, 2, 1, [4, 5, 6, 9], 4] 

In [119]: tt.index(4,2,7)

Out[119]: 6

In [118]: tt.index(4,2,6)

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-118-900c1655e582> in <module>()

----> 1 tt.index(4,2,6)

ValueError: 4 is not in list


L.reverse()  倒序

备注:不是value排序,只是index倒个顺序,对列表的数据结构没要求,注意和sort的区别


打印1:简单列表

tt = [1,2,3]

In [142]: for i in tt:

   .....:     print(i)

   .....:     

1

2

3

打印2:value是成对出现时

tt=[(2,3),(4,5),(6,7)]

In [147]: for a,b in tt:

   .....:     print(a,b)

   .....:     

2 3

4 5

6 7

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档