列表
是一种用于保存一系列有序项目的集合,也就是说,你可以利用列表保存一串项目的序列。想象起来也不难,你可以想象你有一张购物清单,上面列出了需要购买的商品,除开在购物清单上你可能为每件物品都单独列一行,在 Python 中你需要在它们之间多加上一个逗号。
项目的列表应该用方括号括起来,这样 Python 才能理解到你正在指定一张列表。一旦你创建了一张列表,你可以添加、移除或搜索列表中的项目。既然我们可以添加或删除项目,我们会说列表是一种可变的(Mutable) 数据类型,意即,这种类型是可以被改变的。
案例(保存为 ds_using_list.py ) :
shoplist = ['apple','mango','carrot','banana']
print('i have',len(shoplist),'item to purchase.')
print('these items are:',end=' ')
for item in shoplist:
print(item,end=' ')
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 item 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 函数时我们使用end 参数
,这样就能通过一个空格来结束输出工作,而不是通常的换行。
接下来,如我们讨论过的那般,我们通过列表对象中的 append
方法向列表中添加一个对象。然后,我们将列表简单地传递给 print
函数,整洁且完整地打印出列表内容,以此来检查项目是否被切实地添加进列表之中。
接着,我们列表的 sort
方法对列表进行排序。在这里要着重理解到这一方法影响到的是列表本身
,而不会返回一个修改过的列表——这与修改字符串的方式并不相同。同时,这也是我们所说的,列表是可变的(Mutable) 而字符串是不可变的(Immutable) 。
随后,当我们当我们在市场上买回某件商品时,我们需要从列表中移除
它。我们通过使用del
语句来实现这一需求。在这里,我们将给出我们希望从列表中移除的商品, del 语句则会为我们从列表中移除对应的项目。我们希望移除列表中的第一个商品,因此我们使用del shoplist[0]
(要记住 Python 从 0 开始计数) 。