前言
本节介绍Python中的列表/序列(List)和字典(Dictionary)知识点。
Lists是Python中最基本的数据结构。序列中的每个元素(items)都分配一个数字,即索引。
为了方便起见,”列表“或”序列“也泛指Lists;
Dictionary是Python中的一种可变容器模型,可存储任意类型对象
下文中,1-8节是介绍List;9-12节是介绍Dictionary;13-14节介绍整体
1、Introduction to Lists
Lists是一个数据类型(datatype),可以存储不同信息作为一个序列。
list_name = [item_1, item_2]
同样的,Lists可以为空
empty_list = []
注:Lists与strings相似,但也有很多不同之处。
zoo_animals = ["pangolin", "cassowary", "sloth", "panda"];
# One animal is missing!
if len(zoo_animals) > 3:
print "The first animal at the zoo is the " + zoo_animals[0]
print "The second animal at the zoo is the " + zoo_animals[1]
print "The third animal at the zoo is the " + zoo_animals[2]
print "The fourth animal at the zoo is the " + zoo_animals[3]
上述代码中,zoo_animals列表有三个元素
2、Access by Index
可以通过索引值(index)来访问列表中的某元素,索引值就像列表中的地址。
格式如下:List_name[index]
zoo+animals[0] #第一个元素
注:index是从0开始,这是科学编程习惯!!!
numbers = [5, 6, 7, 8]
print "Adding the numbers at indices 0 and 2..."
print numbers[0] + numbers[2]
print "Adding the numbers at indices 1 and 3..."
# Your code here!
print numbers[1] + numbers[3]
3、New Neighbors
访问/调用/改变列表中的元素