首页 > 编程语言 > 详细

Python序列之列表(list)

时间:2016-01-19 12:23:08      阅读:139      评论:0      收藏:0      [点我收藏+]

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

创建一个列表

  list1 = [‘a‘,‘b‘,‘c‘,‘d‘,‘e‘]

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

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

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

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

append

 1 功能:列表添加元素,添加至列表末尾
 2 语法: L.append(object) -- append object to end
 3 L = [a,c,b,d]
 4 L.append(e)
 5 结果:L
 6 [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

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

extend

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

index

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

 insert

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

pop

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

remove

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

reverse

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

sort

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

 L1 + L2

 1 功能:合并两个列表,返回一个新的列表,原列表不变
 2 语法:L = L1 + L2 -> list
 3 L1 = [a,b,c]
 4 L2 = [1,2,3]
 5 L = L1 + L2
 6 结果:
 7 print L
 8 [a,b,c,1,2,3]
 9 print L1
10 [a,b,c]
11 print L2
12 [1,2,3]

L * n

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

 

 

Python序列之列表(list)

原文:http://www.cnblogs.com/spiritman/p/5141598.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!