Python2 列表方法
来源:互联网 发布:mindnode有windows版么 编辑:程序博客网 时间:2024/05/31 06:21
方法调用方式:
对象.方法(参数)
1、append(obvject)
append 方法用于在列表的末尾追加新的对象
例:
py = list('pytho')print 'py的值为:',py打印结果:py的值为: ['p', 'y', 't', 'h', 'o']py.append('n')print pyprint 'py的值为:',py打印结果:py的值为: ['p', 'y', 't', 'h', 'o', 'n']
2、count(value)
count方法用于统计某个元素在列表中出现的次数
例:
num = list('122334455')num.cunt('2')打印结果:2
3、extend()
extend方法用于在列表的末尾一次性追加另一个序列中的多个值
例:
a = [1,2,3]print 'a的值:',a打印结果:a的值: [1, 2, 3]b = [4,5,6]a.extend(b[:2])print 'a的值:', a打印结果:a的值: [1, 2, 3, 4, 5]
4、index(value,start,stop)
index方法用于从列表中找出某个值第一个匹配项的索引位置
例:
>py = list('python')>py.index('h')>3
5、insert(index,object)
insert方法用于将对象插入到列表中
参数:index为插入对象在列表中的位置
例:
>py = list('pythn')>py>['p', 'y', 't', 'h', 'n']>py.insert(4,'o')>py> ['p', 'y', 't', 'h', 'o', 'n']
6、pop(index)
pop方法会移除列表中的一个元素,并返回该元素的值,默认为移除最后一个元素
例:
>py = list('python')>py> ['p', 'y', 't', 'h', 'o', 'n']>py.pop()>'n'>py.pop(0)>'p'
7、remove()
remove方法用于移除列表中某个值得第一个匹配项
例:
>py = list('python')>py>['p', 'y', 't', 'h', 'o', 'n']>py.remove('p')>py>['y', 't', 'h', 'o', 'n']>py.remove('p')>ValueError: list.remove(x): x not in list #说明当删除的值不在列表
8、reverse()
reverse方法将列表中的元素反向,该方法改变列表但是不返回值
例:
>py = list('python')>py>['p', 'y', 't', 'h', 'o', 'n']>py.reverse()>py>['n', 'o', 'h', 't', 'y', 'p']>py[::-1]>['p', 'y', 't', 'h', 'o', 'n']
9、sort(cmp = None, key = None, reverse = false)
sort方法用于对列表排序,默认升序,不返回值。
例:
>x = [2,5,1,6,9,4]>x.sort()>x> [1, 2, 4, 5, 6, 9]#获取排序副本>x = [2,5,1,6,9,4]>y = x[:]>y.sort()>y>[1, 2, 4, 5, 6, 9]#用sorted获取排序副本>x = [2,5,1,6,9,4]>y = sorted(x)>y>[1, 2, 4, 5, 6, 9]#逆排序x = [2,5,1,6,9,4]y = x.sort(reverse = Ture)y#使用函数排序x = ['ddd','ssss','d']x.sort(key = len)x['d', 'ddd', 'ssss']
阅读全文
0 0
- Python2 列表方法
- Python2.7 学习笔记1-列表
- 基于Python2.7进行的列表排序
- Python2.7刷基础Day2----列表,字典
- Python2 列表 (list)的基本操作
- Python2和Python3切换方法
- CentOS安装Python2.7与Python2.6并存的方法
- python2
- Python2
- Python2
- python2
- python2
- Python2
- python2
- 像计算机科学家一样思考python2 笔记 - 列表 list
- python2 lambda内赋值打印方法
- python2 类及其函数、方法 的问题
- 【编码】Python2.x的中文显示方法
- 代码分析基类和派生类的地址和布局的问题
- Codeforces 600E Lomsat gelral (启发式合并)
- java将数据写入csv文件,从csv文件中读取数据
- 控制台程序生成窗口
- CodeForces
- Python2 列表方法
- [bzoj1055][HAOI2008]玩具取名(区间dp)
- ZooKeeper源码(3)server包非核心类
- ss安装并开启BBR算法
- NOI 2002 机器人M号 欧拉函数
- opencv-python(1):读入、显示、保存图像
- 2015ACM/ICPC亚洲区沈阳站-重现赛(感谢东北大学) Meeting(SPAF+拆点)
- 表格
- 最大的矩形