首页 > 技术文章 > list列表函数

zhaojingjing302 2019-08-22 09:54 原文

建立列表

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

访问list中的值  :列表索引从0开始正序【0,1,2,3......】或倒序【..........-3,-2,-1】

list1[0]:  physics        
list2[1:5]:  [2, 3, 4, 5]

更新list

list = []          ## 空列表
list.append('Google')   ## 使用 append() 添加元素
list.append('Runoob')
print list

 

删除list的值

list1 = ['physics', 'chemistry', 1997, 2000]
print list1
del list1[2]
print "After deleting value at index 2 : "
print list1

remove()方法

Python列表脚本操作符

Python 表达式结果描述
len([1, 2, 3]) 3 长度
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] 组合
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 重复
3 in [1, 2, 3] True 元素是否存在于列表中
for x in [1, 2, 3]: print x, 1 2 3 迭代

Python列表函数&方法

序号函数
1 cmp(list1, list2)
比较两个列表的元素
2 len(list)
列表元素个数
3 max(list)
返回列表元素最大值
4 min(list)
返回列表元素最小值
5 list(seq)
将元组转换为列表

方法

序号方法
1 list.append(obj)
在列表末尾添加新的对象
2 list.count(obj)
统计某个元素在列表中出现的次数
3 list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4 list.index(obj)
从列表中找出某个值第一个匹配项的索引位置
5 list.insert(index, obj)
将对象插入列表
6 list.pop([index=-1])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7 list.remove(obj)
移除列表中某个值的第一个匹配项
8 list.reverse()
反向列表中元素
9 list.sort(cmp=None, key=None, reverse=False)
对原列表进行排序

推荐阅读