Python编程从入门到实践(第2版)第三章 列表简介

《 Python编程:从入门到实践 》(第2版)[美]埃里克·马瑟斯(Eric Matthes)

3.1 列表是什么

在Python中,用方括号[]表示列表,并用逗号分隔其中的元素。示例如下,其中包括几个名字:
输入:

names = ['lilei','wangquan','fanfu']
print(names)

输出:

 ['lilei','wangquan','fanfu']

3.1.1 访问列表元素

只需要将列表中该元素的位置(索引)告诉Python即可。三个要素如下必不可缺:

  1. 列表名称;
  2. 元素索引;
  3. 方括号;

下面的代码从列表名字names中提取第一个名字:
输入:

names = ['lilei','wangquan','fanfu']
print(names[0])

输出:

lilei

3.1.2 索引从0而不是1开始

在Python中,第一个列表元素的索引为0,而不是1。
第二个列表元素的索引为1。
输入:

#访问列表元素、索引从0开始
names = ['lilei','wangquan','fanfu']
print(names[0])
print(names[1])
print(names[2])
print(names[-1]) # 索引-1和2是同样效果,访问最后一个元素
print(names[-2]) # 索引-2和1是同样效果,访问倒数第二个元素
print(names[-3]) # 索引-3和0是同样效果,访问倒数第三个元素

输出:

lilei
wangquan
fanfu
fanfu
wangquan
lilei

3.1.3 使用列表中的各个值

输入:

names = ['lilei','wangquan','fanfu']
message0 = f"{names[0].title()} is my first friend" # 使用f字符串,并把名字首字母大写
message1 = f"{names[1].title()} is my second friend"
message2 = f"{names[2].title()} is my third friend"
print(message0)
print(message1)
print(message2)

输出:

Lilei is my first friend
Wangquan is my second friend
Fanfu is my third friend

3.2 修改、添加和删除元素

3.2.1 修改列表元素

输入:

# 修改摩托车列表的第一个元素的值'honda',变成'ducati'
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)

motorcycles[0] = 'ducati' #可以修改任意列表元素的值,而不仅仅是第一个元素的值
print(motorcycles)

输出:

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

3.2.2 在列表中添加元素

1.在列表末尾添加元素

将元素**附加(append)**到非空白列表末尾
输入:

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)

motorcycles.append('ducati') #在列表末尾添加'ducati'
print(motorcycles)

输出:

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

将元素依次**附加(append)**到空白列表末尾
输入:

#在空白列表末尾添加元素
motorcycles = []

motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')

print(motorcycles)

输出:

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

2.在列表中插入元素

使用insert()可在列表的任何位置添加新元素·。
输入:

motorcycles = ['honda','yamaha','suzuki']

motorcycles.insert(0,'ducati') # 使得列表中既有每个元素都右移一个位置
print(motorcycles)

输出:

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

3.2.3 从列表中删除元素

1.使用del语句删除元素

输入:

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)

del motorcycles[0]
print(motorcycles)

输出:

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

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

方法pop()删除列表末尾的元素,并让你能够接着使用它。
下面从列表motorcycles中弹出一款摩托车:
输入:

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)

popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)

输出:

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

3.弹出列表中任何位置处的元素

用pop()来删除列表中任意位置的元素,只需要在圆括号内指定要删除元素的索引即可。
输入:

motorcycles = ['honda','yamaha','suzuki']

first_owned = motorcycles.pop(0) #弹出第一款摩托车,该摩托车就已不在列表中了
print(f"The first motorcycle I owned was a {first_owned.title()}.") #描述购买的第一辆摩托车

输出:

The first motorcycle I owned was a Honda.

4.根据值删除元素

不知道所要删除值的位置,但知道要删除的元素的值,可以使用方法remove()
输入:

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

motorcycles.remove('ducati')
print(motorcycles)

输出:

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

使用remove从列表中删除元素时,也可接着使用它的值。
下面删除’ducati‘,并说明原因
输入:

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

too_expensive = 'ducati' #将'ducati'赋给变量too_expensive
motorcycles.remove(too_expensive) #删除'ducati'
print(motorcycles)
print(f"\nA {too_expensive.title()} is too expensive for me.") #指出将'ducati'从列表中删除的原因

输出:

A Ducati is too expensive for me.

动手试一试

练习3-4:嘉宾名单
邀请列表中的三个最想邀请的人共进晚餐
输入:

names = ['lilei','wangtong','chenqi','duanhui',]

full_persons = f"{names[0]} {names[1]} {names[2]}" #使用f字符串
print(f"\nThe people most wanted to invite are {full_persons.title()}.")

输出:

The people most wanted to invite are Lilei Wangtong Chenqi.

练习3-5:修改嘉宾名单
输入:

names = ['lilei','wangtong','chenqi','duanhui',]

print(f"{names[0].title()} can't go.")  #lilei无法赴约
full_persons = f"{names[1]} {names[2]} {names[3]}" #duanhui可以赴约
print(f"\nThe people most wanted to invite are {full_persons.title()}.")

输出:

Lilei can't go.
The people most wanted to invite are Wangtong Chenqi Duanhui.

练习3-6:添加嘉宾
输入:

names = ['lilei','wangtong','chenqi','duanhui',]

names.insert(0,'wangdasi') # 将一名新的嘉宾添加到名单开头
names.insert(1,'liyifan') # 将另一名新的嘉宾添加到名单中间
names.append('fanfu') # 将最后一位新嘉宾添加到名单末尾
print(f"{names[0].title()},I want you to have dinner with me")
print(f"{names[1].title()},I want you to have dinner with me")
print(f"{names[2].title()},I want you to have dinner with me")
print(f"{names[3].title()},I want you to have dinner with me")
print(f"{names[4].title()},I want you to have dinner with me")
print(f"{names[5].title()},I want you to have dinner with me")
print(f"{names[6].title()},I want you to have dinner with me")

输出:

Wangdasi,I want you to have dinner with me
Liyifan,I want you to have dinner with me
Lilei,I want you to have dinner with me
Wangtong,I want you to have dinner with me
Chenqi,I want you to have dinner with me
Duanhui,I want you to have dinner with me
Fanfu,I want you to have dinner with me

练习3-7:缩减名单
输入:

print(f"I have to tell everyone I only can invite two people.") #通知只能邀请两名
delete_one = names.pop(6)
print(f"{delete_one.title()},I am sorry I can't invite you to diner.")
delete_two = names.pop(5)
print(f"{delete_two.title()},I am sorry I can't invite you to diner.")
delete_three = names.pop(4)
print(f"{delete_three.title()},I am sorry I can't invite you to diner.")
delete_four = names.pop(3)
print(f"{delete_four.title()},I am sorry I can't invite you to diner.")
delete_five = names.pop(2)
print(f"{delete_five.title()},I am sorry I can't invite you to diner.")
print(f"{names[0].title()},you are still invited.") #通知余下两位仍在受邀人之列
print(f"{names[1].title()},you are still invited.") #通知余下两位仍在受邀人之列
print(names)
names.remove('wangdasi') # 把名单变成空的
names.remove('liyifan')
print(names)

输出:

I have to tell everyone I only can invite two people.
Fanfu,I am sorry I can't invite you to diner.
Duanhui,I am sorry I can't invite you to diner.
Chenqi,I am sorry I can't invite you to diner.
Wangtong,I am sorry I can't invite you to diner.
Lilei,I am sorry I can't invite you to diner.
Wangdasi,you are still invited.
Liyifan,you are still invited.
['wangdasi', 'liyifan']
[]

3.3 组织列表

3.3.1 使用方法sort()对列表永久排序

假设汽车列表中的所有值都是小写的。
输入:

cars = ['bmw','audi','toyota','subaru']
cars.sort()#使用sort()对列表按字母反顺序永久排序
print(cars)

cars = ['bmw','audi','toyota','subaru']
cars.sort(reverse=True) #使用sort(reverse=True)对列表按字母反顺序永久排序
print(cars)

输出:

['audi', 'bmw', 'subaru', 'toyota']
['toyota', 'subaru', 'bmw', 'audi']

3.3.2 使用函数sorted()对列表临时排序

函数sorted()让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。
以汽车列表为例:
输入:

cars = ['bmw','audi','toyota','subaru']

print("Here is the original list:") #原来顺序打印
print(cars)

print("\nHere is the sorted list:") # 按字母顺序临时打印
print(sorted(cars))

print("\nHere is the original list again:") # 再次打印,核实排列顺序未变
print(cars)

输出:

Here is the original list:
['bmw','audi','toyota','subaru']

Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']

Here is the original list again:
['bmw','audi','toyota','subaru']

3.3.3 倒着打印列表

reverse()可以反转列表元素的排列顺序
假设汽车是按照购买顺序排列的,可轻松地按照相反的顺序排列其中的汽车。
输入:

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

cars.reverse() #reverse()可以反转列表元素的排列顺序
print(cars)

输出:

['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

3.3.4 确认列表的长度

输入:

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

输出:

4

动手试一试

练习3-8:放眼世界
想出至少5个你渴望去旅游的地方。
输入:

tourist_attractions = ['guilin','zhangjiajie','shenzhen','beijing','xinjiang']

print("Here is the original list:") #原来顺序打印
print(tourist_attractions)

print("\nHere is the sorted list:") # 按字母顺序临时打印
print(sorted(tourist_attractions))

print("\nHere is the original list again:") # 再次打印,核实排列顺序未变
print(tourist_attractions)

tourist_attractions.reverse() # 倒着打印列表
print(tourist_attractions)
tourist_attractions.reverse() # 恢复打印列表
print(tourist_attractions)

tourist_attractions.sort() # 对列表按字母永久排序
print(tourist_attractions)

tourist_attractions.sort(reverse=True) # 对列表按字母顺序相反的顺序排列
print(tourist_attractions)

输出:

Here is the original list:
['guilin', 'zhangjiajie', 'shenzhen', 'beijing', 'xinjiang']
Here is the sorted list:
['beijing', 'guilin', 'shenzhen', 'xinjiang', 'zhangjiajie']
Here is the original list again:
['guilin', 'zhangjiajie', 'shenzhen', 'beijing', 'xinjiang']
['xinjiang', 'beijing', 'shenzhen', 'zhangjiajie', 'guilin']
['guilin', 'zhangjiajie', 'shenzhen', 'beijing', 'xinjiang']
['beijing', 'guilin', 'shenzhen', 'xinjiang', 'zhangjiajie']
['zhangjiajie', 'xinjiang', 'shenzhen', 'guilin', 'beijing']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值