第3章 列表简介

学习目标

  • 列表是什么,以及如何使用其中的元素。
  • 如何定义列表,如何增删元素,以及如何对列表进行永久排序和临时排序。
  • 如何获得列表的长度,以及如何在使用列表时避免索引错误。

3.1 列表是什么

列表(list)由一系列按特定顺序排列的元素组成,用方括号[]表示,并用小写逗号,分隔其中的元素。

列表能将相同或不同类型的数据组合到一起。由于列表通常包含不止一个元素,因此列表名称最好用复数。

一个简单示例:

bicycles = ['trek','cannondale','readline','specialized']
print(bicycles)
>>>
['trek','cannondale','readline','specialized']

访问列表中的元素

列表是有序集合,要访问列表的任何元素,只需将该元素的位置,即索引(index)告诉Python即可。

索引:通过字符串中值所处的位置对值进行选取。从 0 而不是 1 开始

>>> bicycles = ['trek', 'cannondale', 'redline', 'specialized']
>>> print(bicycles[1])
cannondale #返回列表中的第二个元素
>>> print(bicycles[3])
specialized #返回列表中的四个元素
>>> print(bicycles[-1])
specialized # 在不知道列表长度情况下访问最后的元素

例如,下面的代码从列表中提取第一款自行车:

bicycles = ['trek','cannondale','readline','specialized']
print(bicycles[0])
>>>
trek

当你请求获取列表元素时,Python只返回该元素,而不包括方括号,正是你要让用户看到的结果——整洁、干净的输出。

你可以对任意列表元素调用第 2 章介绍的字符串方法。例如,可使用title()方法让元素'trek'的格式更标准。

>>> bicycles = ['trek', 'cannondale', 'redline', 'specialized']
>>> print(bicycles[3].title()) # 输出首字母大写的 Specialized
Specialized

也可以像使用其他变量一样使用列表中的各个值。例如,使用f字符串创建消息:

>>> message = f"My first bicycle was a {bicycles[0].title()}."
>>> print(message) # 输出 My first bicycle was a Trek.
My first bicycle was a Trek.

3.2 列表元素的增删改

修改元素

# 更改列表中的第一个元素
>>> motorcycles = ['honda','yamaha','suzuki']
>>> motorcycles[0] = 'ducati'
>>> print(motorcycles)

['ducati', 'yamaha', 'suzuki']

添加元素

  1. append()方法:在列表末尾追加元素,轻松创建动态列表
>>> motorcycles = []
>>> motorcycles.append('honda')
>>> motorcycles.append('yamaha')
>>> motorcycles.append('suzuki')
>>> print(motorcycles)

['honda', 'yamaha', 'suzuki']

这种建立列表的方法很常见,因为通常在程序运行之前,你并不知道用户想要在程序中存储哪些数据。要让用户掌握控制权,首先要定义一个空列表,用于保存用户的值。然后将提供的每个新值追加到刚刚创建的列表中。

  1. insert() 方法:在列表的指定位置插入新元素(将元素插入列表)

需要指定新元素的索引和值。在索引处打开一个空格,并在该位置存储元素的值,该操作会将列表中的其他数值向右移动一个位置。

>>> motorcycles = ['honda','yamaha','suzuki']
>>> motorcycles.insert(0,'ducati')
>>> print(motorcycles)
 
['ducati','honda', 'yamaha', 'suzuki']

删除元素

  1. 使用del语句删除元素

如果知道要删除元素的索引,可使用del删除列表任意位置处的元素,删除后无法再访问。

  1. 使用pop()方法删除元素

术语弹出(pop)源自这样的类比:列表就像一个栈,删除列表末尾的元素相当于弹出栈顶元素。

删除并返回列表中指定索引(默认为末尾)的元素,但弹出(pop)的值能被接着使用。在括号内指定要删除元素的索引即可删除列表中任意位置的元素。

>>> motorcycles = ['honda','yamaha','suzuki']
>>> del motorcycles[0] # 删除了honda
>>> print(motorcycles)
['yamaha', 'suzuki']

>>> popped_motorcycle = motorcycles.pop()#从列表中弹出一个值,并将其赋给变量 popped_motorcycle
>>> print(motorcycles)
['yamaha']
>>> print(popped_motorcycle)# motorcycles列表末尾的suzuki已被移除,并赋值到新变量打印
suzuki
# 使用示例
>>> motorcycles = ['honda','yamaha','suzuki']
>>> last_owned = motorcycles.pop()
>>> print(f'The last motorcycle I owned was a {last_owned.title()}.')
The last motorcycle I owned was a Yamaha.

如果你要删除元素后不再以任何方式使用它,就使用del语句;如果你要删除元素后还能继续使用它,就使用pop()方法。

  1. remove()方法:根据值删除元素,删除列表中匹配到的第一个指定元素。

只知道要删除的值,不知道要移除的值所处的位置,使用remove()

>>> motorcycles = ['honda','yamaha','ducati','suzuki']
>>> motorcycles.remove('ducati')
>>> print(motorcycles)
['honda', 'yamaha', 'suzuki']

>>> motorcycles = ['honda','yamaha','ducati','suzuki']
>>> too_expensive = 'ducati'
>>> motorcycles.remove(too_expensive)
>>> print(motorcycles)
['honda', 'yamaha', 'suzuki']
>>> print(f"\nA {too_expensive.title()} 对我来说太贵了。")
A Ducati 对我来说太贵了。

remove()方法只删除指定值的第一次出现。如果值在列表中出现不止一次,就需要使用循环来确保所有出现的值将被删除。您将在后续内容中学习如何操作。

列表管理

元素排序常常无法预测,用户提供数据的顺序不受控制,但你需要以特定顺序展示信息。Python 提供了很多管理列表的方式, 可根据具体情况选用。

  1. 对列表进行永久排序

sort() 方法:对列表永久性排序。还可以按与字母顺序相反的顺序排列列表元素,只需向sort()方法传递参数reverse=True即可。

>>> cars = ['bmw', 'audi', 'toyota', 'subaru']
>>> cars.sort()
>>> print(cars)
['audi', 'bmw', 'subaru', 'toyota']
>>> cars.sort(reverse=True) # True的首字母必须大写
>>> print(cars)
['toyota', 'subaru', 'bmw', 'audi']
  1. 对列表进行临时排序

sorted()函数:让列表按特定顺序显示元素,同时不影响原始排列顺序。同样,如果要按与字母顺序相反的顺序显示列表,也可向函数sorted()传递参数reverse=True

>>> cars = ['bmw', 'audi', 'toyota', 'subaru']
>>> print(sorted(cars))
['audi', 'bmw', 'subaru', 'toyota']

>>> print(cars)
['bmw', 'audi', 'toyota', 'subaru']

>>> print(sorted(cars,reverse=True))
['toyota', 'subaru', 'bmw', 'audi']

注意:在并非所有的值都是小写时,按字母顺序排列列表要复杂些。决定排列顺序时,有多种解读大写字母的方式,要指定准确的排列顺序,可能比我们这里所做的要复杂。 sort()sorted()中文排序就是参照字符编码(Unicode),而非拼音。

  1. 反向打印列表

reverse() :永久性地翻转列表元素的排列顺序,并不是按字母顺序向后排序,恢复原来排序只需再次调用即可。

>>> cars = ['bmw','audi','toyota','subaru']
>>> print(cars)
['bmw','audi','toyota','subaru']

>>> cars.reverse()
>>> print(cars)
['subaru', 'toyota', 'audi', 'bmw']
  1. 确定列表长度
    len()函数:快速获悉列表的长度,计算列表元素数时从1开始,因此在确定列表长度时应该不会遇到差一错误,而查看列表或其包含的元素数,反而可帮助你排查索引错误。
>>> cars = ['bmw','audi','toyota','subaru']
>>> print(cars[4])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

>>> len(cars)
4

动手一试

姓名:把一些朋友的姓名存储在一个列表中,并将其命名为names。依次访问该列表的每个元素,从而将每个朋友的姓名都打印出来。

names = ['ron','tyler','dani']
print(names[0])
print(names[1])
print(names[2])

问候语:继续使用上述列表,但不打印每个朋友的姓名,为每人打印一条消息。每条消息包含相同问候语,但抬头为相应朋友的姓名。

names = ['ron','tyler','dani']
print(f"hello, {names[0].title()}!")
print(f"Hello, {names[1].title()}!" )
print(f"Hello, {names[2].title()}!")

自己的列表:想想你喜欢的通勤方式,如骑摩托车或开汽车,并创建一个包含多种通勤方式的列表。根据列表打印一系列有关这些通勤方式的陈述,例如:I would like to own a Honda motorcycle.

commute = ["bus","motorcycle","bike","walk"]
print(f"I would like to own {commute[0]}")

嘉宾名单:若你可以邀请任何人一起共进晚餐(无论在世还是故去),你会邀请哪些人?请创建一个列表,其中包含至少三个你想邀请的人,然后使用这个列表打印消息,邀请这些人都来与你共进晚餐。

guests = ['guido van rossum', 'jack turner', 'lynn hill']
name = guests[0].title()
print(f"{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")

修改嘉宾名单:你刚得知有位嘉宾无法赴约,因此需要邀请另一位嘉宾。

# 在上述代码基础上继续输入:
# Jack 无法赴约,转而邀请 Gary
del(guests[1])
guests.insert(1, 'gary snyder')
# 重新打印邀请函
name = guests[0].title()
print(f"\n{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")

添加嘉宾:你刚找到一张更大的餐桌,可容纳更多嘉宾就座。想想你还想邀请哪三位嘉宾。在程序末尾添加函数调用print(),指出你找到一张更大的餐桌。

# 在上述代码基础上继续输入:
# 找到了更大的餐桌,再邀请一些嘉宾
print("\nWe got a bigger table!")
guests.insert(0, 'frida kahlo')
guests.insert(2, 'reinhold messner')
guests.append('elizabeth peratrovich')
name = guests[0].title()
print(f"{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
name = guests[2].title()
print(f"{name}, please come to dinner.")
name = guests[3].title()
print(f"{name}, please come to dinner.")
name = guests[4].title()
print(f"{name}, please come to dinner.")
name = guests[5].title()
print(f"{name}, please come to dinner.")

缩短名单:你刚得知新购买的餐桌无法及时送达,因此只能邀请两位嘉宾。

# 在上述代码基础上继续输入:
# 糟糕,餐桌无法及时送达!
print("\nSorry, we can only invite two people to dinner.")
name = guests.pop()
print(f"Sorry, {name.title()} there's no room at the table.")
name = guests.pop()
print(f"Sorry, {name.title()} there's no room at the table.")
name = guests.pop()
print(f"Sorry, {name.title()} there's no room at the table.")
name = guests.pop()
print(f"Sorry, {name.title()} there's no room at the table.")
# 应该只剩下两位嘉宾了,向他们发出邀请
name = guests[0].title()
print(f"{name}, please come to dinner.")
name = guests[1].title()
print(f"{name}, please come to dinner.")
# 清空名单
del(guests[0])
del(guests[0])
# 核实名单是空的
print(guests)

放眼世界:想出 5 个你想去旅游的地方。

locations = ['himalaya', 'andes', 'tierra del fuego', 'labrador', 'guam']
print(f"Original order:\n{locations}")

print(f"\nAlphabetical:\n{sorted(locations)}")
print(f"\nOriginal order:\n{locations}")

print(f"\nReverse alphabetical:\n{sorted(locations, reverse=True)}")
print(f"Original order:\n{locations}")

print(f"\nReversed:\n{locations.reverse()}")

print(f"\nAlphabetical\n{locations.sort()}")

print(f"\nReverse alphabetical\n{locations.sort(reverse=True)}")

locations = ['himalaya', 'andes', 'tierra del fuego', 'labrador', 'guam']
print("Original order:")
print(locations)

print("\nAlphabetical:")
print(sorted(locations))
print("\nOriginal order:")
print(locations)

print("\nReverse alphabetical:")
print(sorted(locations, reverse=True))
print("\nOriginal order:")
print(locations)

print("\nReversed:")
locations.reverse()
print(locations)

print("\nOriginal order:")
locations.reverse()
print(locations)

print("\nAlphabetical")
locations.sort()
print(locations)

print("\nReverse alphabetical")
locations.sort(reverse=True)
print(locations)

尝试使用各个函数:想想可存储到列表中的东西,如山川、河流、国家、城市、语言或你喜欢的任何东西。编写一个程序,在其中创建一个包含这些元素的列表。然后,至少把本章介绍的每个函数都使用一次来处理这个列表。