Python Day 2 2020-4-6
Python列表简介
列表是什么
1.列表由一系列按特定顺序排列的元素组成。你可以创建包含字母表中所有字母、数字0~9或所有家庭成员姓名的列表;也可以将任何东西加入列表中,其中的元素之间可以没有任何关系。
2.在Python中,用方括号([])来表示列表,并用逗号来分隔其中的元素。
访问列表元素
列表是有序集合,因此要访问列表的任何元素,只需将该元素的位置或索引告诉Python即可。要访问列表元素,可指出列表的名称,再指出元素的索引,并将其放在方括号内。
例如:
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])
索引从 0 而不是 1 开始
使用列表中的各个值
修改、添加和删除元素
修改列表元素:
修改列表元素的语法与访问列表元素的语法类似。要修改列表元素,可指定列表名和要修改的元素的索引,再指定该元素的新值。
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
在列表中添加元素:
1.在列表尾添加元素:append()
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
2.在列表中插入元素:insert()
使用方法insert()可在列表的任何位置添加新元素。为此,你需要指定新元素的索引和值。
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
从列表中删除元素:
1.使用del语句删除元素
使用del语句将值从列表中删除后,就无法再访问了
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
2.使用方法pop()删除元素
方法pop()可删除列表末尾的元素,并让你能够接着使用它。
术语弹出(pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。
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() + '.')
4.根据值删除元素:remove()
不知道要从列表中删除的值所处的位置。如果只知道要删除的元素的值,可使
用方法remove()。
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
PS:方法remove()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。
组织列表
1.使用方法 sort()对列表进行永久性排序
方法sort()永久性地修改了列表元素的排列顺序。再也无法恢复到原来的排列顺序。按字母顺序排列。
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
还可以按与字母顺序相反的顺序排列列表元素,为此,只需向sort()方法传递参数
reverse=True。
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
2.使用函数 sorted()对列表进行临时排序
要保留列表元素原来的排列顺序,同时以特定的顺序呈现它们,可使用函数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)
调用函数sorted()后,列表元素的排列顺序并没有变。如果要按与字母顺序相反的顺序显示列表,也可向函数sorted()传递参数reverse=True。
3.倒着打印列表:reverse()
要反转列表元素的排列顺序,可使用方法reverse()。
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
方法reverse()永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,为此只需对列表再次调用reverse()即可。
4.确定列表的长度
使用函数len()可快速获悉列表的长度。
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(len(cars))
使用列表时避免索引错误
每当需要访问最后一个列表元素时,都可使用索引-1,仅当列表为空时,这种访问最后一个元素的方式才会导致错误。
课后练习
3-1 姓名:将一些朋友的姓名存储在一个列表中,并将其命名为 names。依次访问该列表中的每个元素,从而将每个朋友的姓名都打印出来。
3-2 问候语:继续使用练习 3-1 中的列表,但不打印每个朋友的姓名,而为每人打印一条消息。每条消息都包含相同的问候语,但抬头为相应朋友的姓名。
3-3 自己的列表:想想你喜欢的通勤方式,如骑摩托车或开汽车,并创建一个包含多种通勤方式的列表。根据该列表打印一系列有关这些通勤方式的宣言,如“I would like to own a Honda motorcycle”。
3-4 嘉宾名单:如果你可以邀请任何人一起共进晚餐(无论是在世的还是故去的),
你会邀请哪些人?请创建一个列表,其中包含至少 3 个你想邀请的人;然后,使用这个列表打印消息,邀请这些人来与你共进晚餐。
3-5 修改嘉宾名单:你刚得知有位嘉宾无法赴约,因此需要另外邀请一位嘉宾。
1.以完成练习 3-4 时编写的程序为基础,在程序末尾添加一条 print 语句,指出哪位嘉宾无法赴约。
2.修改嘉宾名单,将无法赴约的嘉宾的姓名替换为新邀请的嘉宾的姓名。
3.再次打印一系列消息,向名单中的每位嘉宾发出邀请。
3-6 添加嘉宾:你刚找到了一个更大的餐桌,可容纳更多的嘉宾。请想想你还想邀请哪三位嘉宾。
1.以完成练习 3-4 或练习 3-5 时编写的程序为基础,在程序末尾添加一条 print 语句,指出你找到了一个更大的餐桌。
2.使用 insert()将一位新嘉宾添加到名单开头。
3.使用 insert()将另一位新嘉宾添加到名单中间。
4.使用 append()将最后一位新嘉宾添加到名单末尾。
5.打印一系列消息,向名单中的每位嘉宾发出邀请。
3-7 缩减名单:你刚得知新购买的餐桌无法及时送达,因此只能邀请两位嘉宾。
1.以完成练习 3-6 时编写的程序为基础,在程序末尾添加一行代码,打印一条你只能邀请两位嘉宾共进晚餐的消息。
2.使用 pop()不断地删除名单中的嘉宾,直到只有两位嘉宾为止。每次从名单中弹出一位嘉宾时,都打印一条消息,让该嘉宾知悉你很抱歉,无法邀请他来共进晚餐。
3.对于余下的两位嘉宾中的每一位,都打印一条消息,指出他依然在受邀人之列。
4.使用 del 将最后两位嘉宾从名单中删除,让名单变成空的。打印该名单,核实程序结束时名单确实是空的。
3-8 放眼世界:想出至少 5 个你渴望去旅游的地方。
1.将这些地方存储在一个列表中,并确保其中的元素不是按字母顺序排列的。
2. 按原始排列顺序打印该列表。不要考虑输出是否整洁的问题,只管打印原始Python 列表。
3.使用 sorted()按字母顺序打印这个列表,同时不要修改它。
4. 再次打印该列表,核实排列顺序未变。
5.使用 sorted()按与字母顺序相反的顺序打印这个列表,同时不要修改它。
6.再次打印该列表,核实排列顺序未变。
7.使用 reverse()修改列表元素的排列顺序。打印该列表,核实排列顺序确实变了。
8. 使用 reverse()再次修改列表元素的排列顺序。打印该列表,核实已恢复到原来的排列顺序。
9.使用 sort()修改该列表,使其元素按字母顺序排列。打印该列表,核实排列顺序确实变了。
10.使用 sort()修改该列表,使其元素按与字母顺序相反的顺序排列。打印该列表,核实排列顺序确实变了。
3-9 晚餐嘉宾:在完成练习 3-4~练习 3-7 时编写的程序之一中,使用 len()打印一条消息,指出你邀请了多少位嘉宾来与你共进晚餐。
3-10 尝试使用各个函数:想想可存储到列表中的东西,如山岳、河流、国家、城市、语言或你喜欢的任何东西。编写一个程序,在其中创建一个包含这些元素的列表,然后,对于本章介绍的每个函数,都至少使用一次来处理这个列表。
names=['na','ting','qiyi','qian','yan']
print(names[0])
print(names[1])
print(names[2])
print(names[3])
print(names[-1])
message="How are you "+names[0].title()+"."
print(message)
message="How are you "+names[1].upper()+"."
print(message)
message="How are you "+names[2].lower()+"."
print(message)
message="How are you "+names[3].title()+"."
print(message)
message="How are you "+names[-1].title()+"."
print(message)
commuter=['bicycle','bus','taxi','drive','metro']
message='I would like to own a '+commuter[0]
print(message)
message='I often take the '+commuter[1]
print(message)
message='I have a '+commuter[2]
print(message)
message='I love '+commuter[3]
print(message)
message='I often take the '+commuter[-1]
print(message)
guests=['na','ting','qiyi','qian','yan']
print(guests[0],guests[1],guests[-1])
print('Welcome to have dinner with me'+guests[0].title()+'.')
print("Welcome to have dinner with me"+guests[2].title()+".")
message="Welcome to have dinner with me"+guests[-1].title()+"."
print(message)
print(guests[-1].title()+" Can't have dinner together.")
guests[-1]='hong'
print(guests)
print('Welcome to have dinner with me '+guests[0].title()+","+guests[2].title()+" and "+guests[-1].title()+'.')
print("I found a bigger table!")
guests.insert(0,'fu')
print(guests)
guests.insert(4,'fu')
print(guests)
guests.append('dong')
print(guests)
print("Unfortunately, my new table didn't arrive, so I had to invite two friends to dinner")
poped_guest=guests.pop()
print(poped_guest.title()+",I'm sorry, but I can't invite you to dinner because the new table didn't arrive.")
poped_guest=guests.pop()
print(poped_guest.title()+",I'm sorry, but I can't invite you to dinner because the new table didn't arrive.")
poped_guest=guests.pop()
print(poped_guest.title()+",I'm sorry, but I can't invite you to dinner because the new table didn't arrive.")
poped_guest=guests.pop()
print(poped_guest.title()+",I'm sorry, but I can't invite you to dinner because the new table didn't arrive.")
poped_guest=guests.pop()
print(poped_guest.title()+",I'm sorry, but I can't invite you to dinner because the new table didn't arrive.")
poped_guest=guests.pop()
print(poped_guest.title()+",I'm sorry, but I can't invite you to dinner because the new table didn't arrive.")
print(len(guests))
print(guests[0].title()+",I will still invite you to have dinner with me.")
print(guests[1].title()+",I will still invite you to have dinner with me.")
del guests[0]
del guests[-1]
print(guests)
travels=['xiamen','beijing','shanghai','wuhan','anhui']
print(travels)
print(sorted(travels))
print(travels)
print(sorted(travels,reverse=True))
print(travels)
travels.reverse()
print(travels)
travels.reverse()
print(travels)
travels.sort()
print(travels)
travels.sort(reverse=True)
print(travels)
foods=['cake','barbecue','ice_cream','milky tea']
print("What I like best is "+foods[0])
print(foods)
foods[-1]='nectar'
print(foods)
foods.append('milky_tea')
print(foods)
foods.insert(2,'kebab')
print(foods)
del foods[1]
print(foods)
poped_food=foods.pop()
print(foods)
print(poped_food)
first_food=foods.pop(0)
print("What I like best is "+first_food+".")
foods.remove('ice_cream')
print(foods)
print(sorted(foods))
print(foods)
foods.sort()
print(foods)
foods.sort(reverse=True)
print(foods)
foods.reverse()
print(foods)
foods.reverse()
print(foods)
print(len(foods))