python中的列表

来源:互联网 发布:冰川网络最新消息 编辑:程序博客网 时间:2024/06/03 17:38
#########################python的列表#####################################
first   列表的创建
way1:利用符号"[]"来创建列表。
way2:通过list函数将其他类型的序列转换为列表。
>>> [1,2,3,4]
[1, 2, 3, 4]
>>> tup=(1,2,3,4,5)
>>> tup=list(tup)
>>> tup
[1, 2, 3, 4, 5]

second  列表的修改
单个元素的修改:索引找到元素重新赋值。
切片修改way1:索引找到一段元素并重新赋值。
                 way2:使用不定长的序列来修改。
for example:
>>> list_a=[1,2,3,4,5]
>>> list_a[0:2]=[7,8]
>>> list_a
[7, 8, 3, 4, 5]
>>> list_a=[1,2,3,4,5]
>>> list_a[1:3]=[]         #相当于删除1,2号元素
>>> list_a
[1, 4, 5]
>>> list_a[0:0]=[11,13]     #相当于添加两个元素
>>> list_a
[11, 13, 1, 4, 5]
>>> list_a[1:3]=list("love")     #段替换
>>> list_a
[11, 'l', 'o', 'v', 'e', 4, 5]
元素的删除way1:使用长度为0的序列替换来删除。
                    way2:利用del语句来删除元素。
for example:
>>> list_b=[1,2,3,4]
>>> del list_a[1]
>>> list_b
[1, 2, 3, 4]
>>> list_b=[1,2,3,4]
>>> del list_b[1]
>>>list_b
[1, 3, 4]
>>> del list_b[1:2]
>>> list_b
[1, 4]

  列表法:
在python中,调用对象的方法的方式为:对象.方法(参数)
1.append方法:可以在一个列表后面追加新的元素.
>>> list_a=[1,2,3]
>>> list_a.append(4)
>>> list_a
[1, 2, 3, 4]
2.count方法:可以查看某个元素在列表中出现的次数。
>>> list_a=[1,2,3,4,1,2,1]
>>> list_a.count(1)
3
3.extend方法:能用其他的列表拓展原有的列表。
>>> list_a=[1,2,3]
>>> list_b=[4,5,6]
>>> list_a.extend(list_b)
>>> list_a
[1, 2, 3, 4, 5, 6]
4.index方法:返回某个元素的索引,若不存在,则会产生错误。
>>> list_a=[1,2,3,88,4,5,6]
>>> list_a.index(88)
3
5.insert方法:在序列的某一个位置插入一个元素。
>>> list_a=[1,2,3,4]
>>> list_a.insert(2,'hello')
>>> list_a
[1, 2, 'hello', 3, 4]
6.pop方法:移除列表某个位置的元素并返回该元素。如果没有定义指定的索引号,默认移除最后一个元素。
>>> list_a=[1,2,3,4]
>>> list_a.pop()
4
7.remove方法:可以一处序列中第一个与参数匹配的元素。
>>> list_a=[1,2,3,4,5,6,4,8]
>>> list_a.remove(4)
>>> list_a
[1, 2, 3, 5, 6, 4, 8]
8.reverse方法:可以将列表改为倒序。
>>> list_a=[1,2,3,4,5,6,4,8]
>>> list_a.reverse()
>>> list_a
[8, 4, 6, 5, 4, 3, 2, 1]
9.sort方法:对列表进行排序。
>>> list_a=[1,2,5,8,9,4,5,2,6]
>>> list_a.sort()
>>> list_a
[1, 2, 2, 4, 5, 5, 6, 8, 9]

notesort()方法默认为升序排列。
###########################The End############################################
原创粉丝点击