1.简介
数据结构基本上就是——它们是可以处理一些 数据 的 结构 。或者说,它们是用来存储一组相关 数据的。 在Python中有三种内建的数据结构——列表、元组和字典。我们将会学习如何使用它们,以及它 们如何使编程变得简单。
2.列表
list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个 序列 的项目。假想你有 一个购物列表,上面记载着你要买的东西,你就容易理解列表了。只不过在你的购物表上,可能 每样东西都独自占有一行,而在Python中,你在每个项目之间用逗号分割。 列表中的项目应该包括在方括号中,这样Python就知道你是在指明一个列表。一旦你创建了一个 列表,你可以添加、删除或是搜索列表中的项目。由于你可以增加或删除项目,我们说列表是 可 变的 数据类型,即这种类型是可以被改变的。
2.1 对象与类的快速入门
列表是使用对象和类的一个例子。当你使用变量i并给它赋值的时候,比如赋整数5,你可以认 为你创建了一个类(类型)int的对象(实例)i。事实上,你可以看一下help(int)以更好 地理解这一点。
类也有方法,即仅仅为类而定义地函数。仅仅在你有一个该类的对象的时候,你才可以使用这些 功能。例如,Python为list类提供了append方法,这个方法让你在列表尾添加一个项目。例 如mylist.append('an item')列表mylist中增加那个字符串。注意,使用点号来使 用对象的方法。
一个类也有域,它是仅仅为类而定义的变量。仅仅在你有一个该类的对象的时候,你才可以使用 这些变量/名称。类也通过点号使用,例如mylist.field。
2.2 使用列表
#!/usr/bin/python
# python3.10
# Filename: using_list.py
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print('I have', len(shoplist), 'items to purchase.')
print('These items are:',)
for item in shoplist:
print(item,)
print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now', shoplist)
print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list is', shoplist)
print('The first item I will buy is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist)
输出:
开始运行...
I have 4 items to purchase.
These items are:
apple
mango
carrot
banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']
运行结束。
变量shoplist是某人的购物列表。在shoplist中,我们只存储购买的东西的名字字符串,也可以在列表中添加 任何种类的对象 包括数甚至其他列表。
我们也使用了for..in循环在列表中各项目间递归。列表也是一个序列。
注意,我们在print语句的结尾使用了一个 逗号 来消除每个print语句自动打印的换行符。这样做有点难看,不过确实简单有效。
接下来,我们使用append方法在列表中添加了一个项目,就如前面已经讨论过的一样。然后我们通过打印列表的内容来检验这个项目是否确实被添加进列表了。打印列表只需简单地把列表传递给print语句,我们可以得到一个整洁的输出。再接下来,我们使用列表的sort方法来对列表