您的位置:首页 > 编程语言 > Python开发

Python序列之列表 (list)

2016-01-19 11:44 531 查看
作者博文地址:http://www.cnblogs.com/spiritman/

  列表是Python中最基本的数据结构,是Python最常用的数据类型。Python列表是任意对象的有序集合,通过索引访问指定元素,第一个索引是0,第二个索引是1,依此类推。列表可变对象,支持异构、任意嵌套。

创建一个列表

  list1 = []        #创建空列表

  list2 = ['a','b','c','d','e']

  list3 = ['a','b','c',1,2,3]

列表支持的操作方法及实例展示

  可以使用dir(list)查看列表支持的所有操作

append

功能:列表添加元素,添加至列表末尾
语法: L.append(object) -- append object to end
L = ['a','c','b','d']
L.append('e')
结果:L
['a','c','b','d','e']
7 l = [1,2,3]
8 L.append(l)
9 结果:L
10['a','c','b','d',[1,2,3]]


count

功能:统计指定元素在列表中的个数
语法: L.count(value) -> integer -- return number of occurrences of value
L = [1,2,3,4,5,5]
L.count(5)
结果:2
l = [1,2,3,4,5,[5,6]]
l.count(5)
结果:1                #只统计第一层的元素个数


extend

功能:迭代字符元素或列表元素
语法: L.extend(iterable) -- extend list by appending elements from the iterable
L= ['a','b','c','d']
l = [1,2,3]
L.extend('e')
结果:L
['a','b','c','d','e']
L.extend(l)                #注意与append的区别
结果:L
['a','b','c','d',1,2,3]


index

功能:定位列表中的指定元素
语法: L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present.
L = ['a','b','c','d']
L.index('c')
结果:2
L.index('f')
结果:Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'f' is not in list


insert

功能:在指定索引位置的元素前面插入新的元素
语法:L.insert(index, object) -- insert object before index
L = ['a','b','c','d']
L.insert(2,'e')
结果:L
['a','b','e','c','d']


pop

功能:删除指定索引值的元素,返回值为当前删除的元素的值。不指定索引值,默认删除最后一个元素
语法:L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range.
L = ['a','b','c','d']
L.pop()
结果:'d'
L.pop(2)
结果:'c'


remove

功能:删除列表中指定的元素
语法:L.remove(value) -- remove first occurrence of value. Raises ValueError if the value is not present.
L = ['a','b','c','d']
L.remove('c')
结果:print L
['a','b','d']


reverse

功能:用于反向列表中的元素
语法:L.reverse() -- reverse *IN PLACE*
L = ['a','b','c','d']
L.reverse()
结果:print L
['d','c','b','a']


sort

功能:对列表中的元素进行排序。
语法:L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
L = ['d','b',1,2,3,'a','d']
L.sort()
结果:print L
[1,2,3,'a','b','c','d']

L = ['d','b',1,2,3,'a','d',['ab','bc']]
L.sort()
结果:print L
[1, 2, 3, ['ab', 'bc'], 'a', 'b', 'd', 'd']


L1 + L2

功能:合并两个列表,返回一个新的列表,原列表不变
语法:L = L1 + L2 -> list
L1 = ['a','b','c']
L2 = [1,2,3]
L = L1 + L2
结果:
print L
['a','b','c',1,2,3]
print L1
['a','b','c']
print L2
[1,2,3]


L * n

功能:重复输出列表n次,返回一个新列表,原列表不变
语法:L = L1 * n
L1 = ['a','b','c','d']
L = L1 * 3
结果:
print L
['a','b','c','d','a','b','c','d','a','b','c','d']
print L1
['a','b','c','d']


作者博文地址:http://www.cnblogs.com/spiritman/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: