Python学习02 列表 List

 

Python学习02 列表 List

Python列表 List

  Python中的列表(List)逗号分隔,方括号包围(comma-separated values (items) between square brackets)。

  一个Python列表例子:

movies = ['Hello', 'World','Welcome']

  在Python中创建列表时,解释器会在内存中创建一个类似于数组的数据结构来存放数据,数据项自下而上堆放(形成一个堆栈)。

列表数据的访问

一般访问索引

  可以像访问数组元素一样取用列表中的元素:用方括号加上索引号,索引号从0开始:

>>> names=['Jack','Meng','Mike']
>>> print(names[0])
Jack
>>>

负数索引

  索引值也可以从后往前,依次是-1,-2,……

  比如:

>>> movies=['hello','world','welcome',10]
>>> movies[-1]
10
>>> movies[-4]
'hello'

切片(slice)操作

  用冒号分隔要访问的数据索引的起点和终点,包含前者,不包含后者

  冒号前面的数字和后面的数字都可以省略,省略前者代表最首,省略后者代表最尾。 

  一段小例子:

movies = ['Hello','World','Welcome']
print(movies)
#positive index
print("index 0: " + str(movies[0]))
#negtive index
print("index -1: " + str(movies[-1]))
#slice
print("slice 0-1: " + str(movies[0:1]))
print("slice all: " + str(movies[:]))
print("slice 2-: " + str(movies[2:]))
print("slice -2: " + str(movies[:-2]))

  这段程序的执行结果是:

  使用切片还可以增加数据或者插入数据,用法很灵活。

#assignment: change the list to 3 items
movies[0:]=['first','second','third']
print(movies)

#insert: change 1 item to 3 items
movies[0:1]=['first01','first02','first03']
print(movies)

#delete: delelte the first 2 items
movies[0:2]=[];
print(movies) 

  执行结果:

列表比数组更强大

  首先,不限制数据类型,列表中各种数据可以混合存储,不一定是同种类型。

  比如下面这样完全没问题:

movies = ['Hello','World','Welcome',10,30.5]

  其次,列表可以嵌套,即列表中的元素也可以是一个列表。

  比如:

movies = ['Hello','World','Welcome',10,30.5,['cat','dog']]

  ['cat','dog']就是列表中的一个项,自己也是一个列表,可以继续往下嵌套。

  访问的时候这样访问:

print(movies[5][1])

  输出dog

List类型的内置方法

  见链接:http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

  在Python Shell中输入:dir(__builtins__)

  可以看到所有的内置函数(BIF)。(注意前面和后面都是两个下划线)。

参考资料

  官网Tutorial:

  http://docs.python.org/2/tutorial/introduction.html#lists

  http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

 

  同事推荐:

  http://zhgdg.gitcafe.com/static/doc/byte_of_python.html

  《Head First Python》(设计模式之后真是爱上了Head First系列的书)。

原文地址:https://www.cnblogs.com/mengdd/p/3183734.html