列表是用[]表示的,可以把列表想象成,各个游戏玩家放在一个列表里,然后对这些游戏玩家进行操作。
可以将按特定顺序的元素排列起来,各个元素用,隔开
如name['a','b','c']
print(name)即可得到输出结果
a b c
列表是有顺序的,想要输出第一个元素,则
print(name[0]) 注意:第一个元素位置是从0开始的
如果想要输入倒数第一个元素的话:那么print(name[-1])即可
fruits=['apple','orange','grape','banana'] message='My favourite fruit is '+fruits[-2].title() print(message)
知道列表的意义和用法之后,我还需要学会如何对列表进行一系列操作,包括
1.修改列表元素:
如下代码可将列表的某个元素修改:
motorcycle=['honda','mamumi','skipper'] motorcycle[0]='anti' print(motorcycle)
输出结果是['anti', 'mamumi', 'skipper']
2.列表末尾添加元素,利用append()这个函数
motorcycle=['honda','mamumi','skipper'] motorcycle.append('dota') print(motorcycle)
输出结果为:['honda', 'mamumi', 'skipper', 'dota']
很多游戏等的程序中都是一个空列表然后不断添加元素:
3.列表中间插入元素,利用insert()这个函数,需要确定插入元素的索引和值
motorcycle=['honda','mamumi','skipper'] motorcycle.insert(1,'lisa') print(motorcycle)
这个代码是将新的元素lisa插在了1的位置
输出结果为:['honda', 'lisa', 'mamumi', 'skipper']
4.列表中删除元素(游戏玩家被射杀了,需要去掉这个游戏玩家)
(1)利用del这个函数,不过需要指定需要被删除的元素的位置
motorcycle=['honda','mamumi','skipper'] del motorcycle[1] print(motorcycle)
输出结果为:['honda', 'skipper']
(2)pop删除元素(这个我好像还是不太了解)
pop删除的是最后一个元素,也可以指定元素位置删除
motorcycles=['honda','mamumi','skipper'] last_owned1=motorcycles.pop() last_owned2=motorcycles.pop(0) print(last_owned1) print(last_owned2)
输出结果为:skipper honda
(3)有时候不知道元素的位置,只知道元素的值,所以根据remove()来删除元素:
motorcycles=['honda','mamumi','skipper'] print(motorcycles) motorcycles.remove('honda') print(motorcycles)
输出结果为:
['honda', 'mamumi', 'skipper']
['mamumi', 'skipper']
5.从入门到实践那本书3-7
只能邀请两个人时:
print('I can just invite two guests') while len(dinner)>2: print(dinner.pop()+" I couldn't invite you to have dinner") for person in dinner: print(person+ ", you are still my list")
输出结果:
['ran', 'andi', 'yuanzi', 'robert', 'dove', 'conan']
I can just invite two guests
conan I couldn't invite you to have dinner
dove I couldn't invite you to have dinner
robert I couldn't invite you to have dinner
yuanzi I couldn't invite you to have dinner
ran, you are still my list
andi, you are still my list
所以可以看到要利用while和for函数进行一个编程(后面要好好练习)
len()函数的作用是
1.作用返回字符串、列表、字典、元组等长度
2.语法:len(str)
3:参数:str:要计算的字符串、列表、字典、元组等
4:返回值:字符串、列表、字典、元组等元素的长度
6.sort()函数,按照字母顺序给列表中的每个元素排序,这个顺序的改变是永久性的
dinner=['andi','rico','dove'] dinner.sort() print(dinner)
输出结果为:
['andi', 'dove', 'rico']
7.按照字母顺序相反的顺序排列元素,只需要向sort()传递参数reverse=True,这也是个永久性的排序
dinner=['andi','rico','dove'] dinner.sort(reverse=True) print(dinner)
输出结果为:['rico', 'dove', 'andi']
8.sorted()函数临时排序
dinner=['lendi','rico','dove'] print(sorted(dinner)) print(dinner)
输出结果:
['dove', 'lendi', 'rico']
['lendi', 'rico', 'dove']
9.reverse()函数:倒着打印列表顺序(也是永久性改变顺序,但是可以再一次反转改变回来)
dinner=['lendi','rico','dove'] dinner.reverse() print(dinner)
输出结果:
['dove', 'rico', 'lendi']