《python从入门到实践》笔记 第3章 列表简介

3.1 列表是什么

列表:由一系列按特定顺序排列的元素组成。创建包含字母表所有字母、数字0-9或所有家庭成员姓名的列表;也可以将任何东西加入列表中,其中的元素之间可以没有任何关系。

用方括号([ ])来表示列表,并用逗号分割其中的元素。

bicycles.py

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

3.1.1 访问列表元素

提供该元素的位置或索引便可以访问列表元素:①列表的名称②元素的索引

bicycles=[‘trek’,‘cannondale','redline','specialized']

print(bicycles[0])

上述演示了访问列表元素的语法

还可以调用第2章介绍的字符串方法

bicycles=[‘trek’,‘cannondale','redline','specialized']

print(bicycles[0].title())

3.1.2 索引从0而不是1开始

在Python中,第一个列表元素的索引为0而不是1,与列表操作的底层实现有关。

例访问索引1和3处的自行车

bicycles=['trek','cannonable','redline','specialized']
print(bicycles[1])
print(bicycles[-1])

将返回第2和第最后一个元素

cannondale
specialized

0

1 2 3/-1
第一个元素 第二个元素 第三个元素 第四个元素/最后一个元素

3.1.3 使用列表中的各个值

例:你可以使用拼接根据列表中的值创建消息

bicycles=['trek','cannondale','redline','specialized']
message="My first bicycle was a"+bicycles[0].title()+"."
print(message)

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

names = ["Alice", "Bob", "Charlie", "David"]
print(names[0])
print(names[1])
print(names[2])
print(names[-1])

3-2问候语:继续使用练习3-1中的列表,但不打印每个朋友的姓名,而为每个人打印一条消息。,每条消息都包含相同的问候语,但抬头应为朋友的姓名。

names = ["Alice", "Bob", "Charlie", "David"]
print("Hello,"+names[0].title()+"!")
print("Hello,"+names[1].title()+"!")
print("Hello,"+names[2].title()+"!")
print("Hello,"+names[-1].title()+"!")

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

# 创建一个包含多种通勤方式的列表
commute_ways = ["motorcycle", "car", "bicycle", "bus"]

# 打印有关这些通勤方式的宣言
print("I would like to own a Honda "+commute_ways[0])
print("I would like to drive a Tesla "+commute_ways[1])
print("I would like to ride a Giant "+commute_ways[2])
print("I would like to take a double - decker "+commute_ways[-1])

3.2 修改、添加和删除元素

3.2.1 修改列表元素

修改元素:指定列表名和要修改的元素的索引,再指定该元素的新值

例:假设有个摩托车列表,其中第一个元素为'honda',如何修改它的值呢?

motorcycles.py

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

3.2.2 在列表中添加元素

1.在列表末尾添加元素

1)最简单模式:将元素附加到列表末尾(给列表附加元素时,它将添加到列表末尾)

motorcycles=['honda','yamha','suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)

方法append()在末尾添加元素

方法append()让动态创建列表易如反掌。例:你可以创建一个空列表,再使用一系列的append()语句添加元素。

motorcycles=[]
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)

2.在列表中插入元素

方法insert()在列表任何位置添加新元素(需要指定新元素的索引和值)

motorcycles=['honda','yamaha','suzuki']
motorcycles.insert(0,'ducati')
print(motorcycles)
#插入到列表开头

3.2.3 从列表中删除元素

1.使用del语句删除元素

del:可删除任何位置的列表元素,条件是知道索引

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

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

方法pop()可删除列表末尾的元素,并让你能够接着使用它的值。术语弹出(pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。

例:从列表motorcycles中弹出一俩摩托车

motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
popped_motorcycle=motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
#从列表中弹出一个值(末尾),存在变量中

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

pop():可删除任何位置的元素,只需在括号中指定要删除的元素的索引。

motorcycles=['honda','yamaha','suzuki']
first_owned=motorcycles.pop(0)
print('The first motorcycle I owned was a'+first_owned.title()+'.')
#弹出了第一款摩托车,然后打印出了一条相关信息
del 从列表删除一个元素,且不再以任何方式使用它
pop() 在删除元素后还要继续使用它

4.根据值删除元素

remove():不知道要从列表中删除的值所处的位置,只知道要删除的元素的值。

例:从列表motorcycles中删除值'ducati'

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

使用remove()删除元素时,也可以接着使用它的值。

motorcycles=['honda','yamaha','suzuki','ducati']
print(motorcycles)
too_expensive='ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA"+too_expensive.title()+"is too expensive for me.")

3-4嘉宾名单:如果你可以邀请任何人一起共进晚餐,你会邀请哪些人?请创建一个列表,其中包含至少3个你想邀请的人;然后,使用这个列表打印消息,邀请这些人来与你共进晚餐。

# 创建包含要邀请嘉宾的列表
guests = ["Albert Einstein", "Marie Curie", "Leonardo da Vinci"]

# 打印邀请消息

 print("Dear "+guests(0)+", I would like to invite you to have dinner with me.")
 print("Dear "+guests(1)+", I would like to invite you to have dinner with me.")
 print("Dear "+guests(-1)+", I would like to invite you to have dinner with me.")

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

  • 以完成练习3-4时编写的程序为基础,在程序末尾添加一条print语句,指出哪位嘉宾无法赴约。
  • 修改嘉宾名单,将无法赴约的嘉宾的姓名替换为新邀请的嘉宾的姓名。
  • 再打印一系列消息,向名单中的每位嘉宾发出邀请。
# 创建包含要邀请嘉宾的列表
guests = ["Albert Einstein", "Marie Curie", "Leonardo da Vinci"]

# 遍历嘉宾列表,打印邀请消息
for guest in guests:
    print(f"Dear {guest}, I would like to invite you to have dinner with me.")

# 指出哪位嘉宾无法赴约
guest_unavailable = "Marie Curie"
print(f"Unfortunately, {guest_unavailable} can't make it to the dinner.")

# 找到无法赴约嘉宾在列表中的索引
index = guests.index(guest_unavailable)
# 新邀请的嘉宾
new_guest = "Stephen Hawking"
# 替换无法赴约的嘉宾
guests[index] = new_guest

# 再次遍历嘉宾列表,打印邀请消息
for guest in guests:
    print(f"Dear {guest}, I would like to invite you to have dinner with me.")

3-6添加嘉宾:你刚找到了一个更大的餐桌,可以容纳更多的嘉宾。请想想你还想邀请哪三位嘉宾。

  • 以完成练习3-4或练习3-5时编写的程序为基础,在程序末尾添加一条print语句,指出你找到了一个更大的餐桌。
  • 使用insert()将一位新嘉宾添加到名单开头。
  • 使用insert()将另一位新嘉宾添加到名单中间。
  • 使用append()将最后一位新嘉宾添加到名单末尾。
  • 打印一系列消息,向名单中的每位嘉宾发出邀请。
# 创建包含要邀请嘉宾的列表
guests = ["Albert Einstein", "Marie Curie", "Leonardo da Vinci"]

# 遍历嘉宾列表,打印邀请消息
for guest in guests:
    print(f"Dear {guest}, I would like to invite you to have dinner with me.")

# 指出哪位嘉宾无法赴约
guest_unavailable = "Marie Curie"
print(f"Unfortunately, {guest_unavailable} can't make it to the dinner.")

# 找到无法赴约嘉宾在列表中的索引
index = guests.index(guest_unavailable)
# 新邀请的嘉宾
new_guest = "Stephen Hawking"
# 替换无法赴约的嘉宾
guests[index] = new_guest

# 再次遍历嘉宾列表,打印邀请消息
for guest in guests:
    print(f"Dear {guest}, I would like to invite you to have dinner with me.")

# 指出找到了更大的餐桌
print("Great news! I've found a bigger table.")

# 定义三位新嘉宾
new_guest1 = "Isaac Newton"
new_guest2 = "Galileo Galilei"
new_guest3 = "Niels Bohr"

# 使用 insert() 将一位新嘉宾添加到名单开头
guests.insert(0, new_guest1)

# 使用 insert() 将另一位新嘉宾添加到名单中间
middle_index = len(guests) // 2
guests.insert(middle_index, new_guest2)

# 使用 append() 将最后一位新嘉宾添加到名单末尾
guests.append(new_guest3)

# 再次遍历嘉宾列表,打印邀请消息
for guest in guests:
    print(f"Dear {guest}, I would like to invite you to have dinner with me.")

3-7缩减名单:你刚得知新购买的餐桌无法及时送达,因此只能邀请俩位嘉宾

  • 以完成练习3-6时编写的程序为基础,在程序末尾添加一行代码,打印一条你只能邀请俩位嘉宾共进晚餐的消息。
  • 使用pop()不断地删除名单中的嘉宾,直到只有俩位嘉宾为止。每次从名单中弹出一位嘉宾时,都打印一条消息,让该嘉宾知悉你很抱歉,无法邀请他来共进晚餐。
  • 对于余下的俩位嘉宾中的每一位,都打印一条消息,指出他仍在受邀人之列。
  • 使用del将最后俩位嘉宾从名单中剔除,让名单变成空的。打印该名单,核实程序结束时名单确实是空的。
# 创建包含要邀请嘉宾的列表
guests = ["Albert Einstein", "Marie Curie", "Leonardo da Vinci"]

# 遍历嘉宾列表,打印邀请消息
for guest in guests:
    print(f"Dear {guest}, I would like to invite you to have dinner with me.")

# 指出哪位嘉宾无法赴约
guest_unavailable = "Marie Curie"
print(f"Unfortunately, {guest_unavailable} can't make it to the dinner.")

# 找到无法赴约嘉宾在列表中的索引
index = guests.index(guest_unavailable)
# 新邀请的嘉宾
new_guest = "Stephen Hawking"
# 替换无法赴约的嘉宾
guests[index] = new_guest

# 再次遍历嘉宾列表,打印邀请消息
for guest in guests:
    print(f"Dear {guest}, I would like to invite you to have dinner with me.")

# 指出找到了更大的餐桌
print("Great news! I've found a bigger table.")

# 定义三位新嘉宾
new_guest1 = "Isaac Newton"
new_guest2 = "Galileo Galilei"
new_guest3 = "Niels Bohr"

# 使用 insert() 将一位新嘉宾添加到名单开头
guests.insert(0, new_guest1)

# 使用 insert() 将另一位新嘉宾添加到名单中间
middle_index = len(guests) // 2
guests.insert(middle_index, new_guest2)

# 使用 append() 将最后一位新嘉宾添加到名单末尾
guests.append(new_guest3)

# 再次遍历嘉宾列表,打印邀请消息
for guest in guests:
    print(f"Dear {guest}, I would like to invite you to have dinner with me.")

# 打印只能邀请两位嘉宾的消息
print("Sorry! The new table won't arrive in time. I can only invite two guests now.")

# 不断弹出嘉宾,直到只剩两位
while len(guests) > 2:
    removed_guest = guests.pop()
    print(f"Dear {removed_guest}, I'm really sorry that I can't invite you to dinner.")

# 向余下的两位嘉宾发送仍被邀请的消息
for guest in guests:
    print(f"Dear {guest}, you are still invited to dinner.")

# 删除最后两位嘉宾
del guests[0]
del guests[0]

# 打印空名单以核实
print(guests)

3.3 组织列表

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

方法sotr():对列表进行排序(永久性改变)。

例:假设你有一个汽车列表,并要让其中的汽车按字母进行排序。为了简化任务,假设均为小写。

cars.py

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

按与字母顺序相反的顺序排列列表元素。只需向sort()方法传递参数reverse=True。

cars=['bmw','audi','toyota','subaru']
cars.sort(reverse=True)
print(cars)

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

函数sortde:①保留列表元素原来的排列顺序②以特定的顺序呈现它们

例:对汽车列表调用这个函数

cars=['bmw','audi','toyota','subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("Here is the original list again:")
print(cars)

调用函数sorted后,列表元素的排列顺序并没有变,如果需要按与字母顺序想法的顺序显示列表,向函数sorted()传递参数reverse=True。

3.3.3倒着打印列表

方法reverse():反转列表元素的排序顺序。

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

①不是指按与字母相反的顺序排列列表元素,只是反转列表元素的排列顺序。

②永久性修改列表元素的排列顺序,但是可随时恢复顺序,只需对列表再次调用reverse即可。

3.3.4确定列表的长度

函数len():快速获悉列表的长度。

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

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

  • 将这些地方存储在一个列表中,并确保其中的元素不是按字母顺序排列的。
  • 按原始排列顺序打印该列表。不用考虑输出是否整洁的问题,只管打印原始Python列表。
  • 使用sorted()按字母顺序打印这个列表,同时不要修改它。
  • 再次打印该列表,核实排列顺序未变。
  • 使用sorted()按与字母顺序相反的顺序打印这个列表,同时不要修改它。
  • 再次打印该列表,核实排列顺序未变。
  • 使用reverse()修改列表元素的排列顺序。打印该列表,核实排列顺序确实变了。
  • 使用reverse()再次修改列表元素的排列顺序排列。打印该列表,核实已恢复到原来的排列顺序。
  • 使用sort()修改该列表,使其元素按字母顺序排列。打印该列表,核实排列顺序确实变了。
  • 使用sort()修改该列表,使其元素按与字母相反的顺序排列。打印该列表, 核实排列顺序确实变了。
# 存储渴望去旅游的地方的列表
travel_places = ["Tokyo", "New York", "Paris", "Sydney", "Cairo"]

# 按原始排列顺序打印该列表
print("原始排列顺序:", travel_places)

# 使用 sorted() 按字母顺序打印这个列表,同时不修改它
print("按字母顺序(sorted):", sorted(travel_places))

# 再次打印该列表,核实排列顺序未变
print("核实原始顺序未变:", travel_places)

# 使用 sorted() 按与字母顺序相反的顺序打印这个列表,同时不修改它
print("按字母相反顺序(sorted):", sorted(travel_places, reverse=True))

# 再次打印该列表,核实排列顺序未变
print("再次核实原始顺序未变:", travel_places)

# 使用 reverse() 修改列表元素的排列顺序
travel_places.reverse()
print("使用 reverse() 后的顺序:", travel_places)

# 使用 reverse() 再次修改列表元素的排列顺序
travel_places.reverse()
print("再次使用 reverse() 恢复原始顺序:", travel_places)

# 使用 sort() 修改该列表,使其元素按字母顺序排列
travel_places.sort()
print("使用 sort() 按字母顺序排列后:", travel_places)

# 使用 sort() 修改该列表,使其元素按与字母相反的顺序排列
travel_places.sort(reverse=True)
print("使用 sort() 按字母相反顺序排列后:", travel_places)

3.4使用列表时避免索引错误

1.含三个元素的列表却要求获取第四个元素。

2.对空列表使用索引-1。

你可能感兴趣的:(python编程从入门到实践,python,前端,javascript)