写在前面的话:
之前也在网上看过python视频,照着视频里讲得那样写了两个小游戏。但觉得自己对基本的语法似懂非懂,没有形成相应的体系。所以会通过这样的形式整理自己的语法知识。基础打牢固才能建好高楼。
目标:
访问单个元素(03)
处理列表所有元素
处理列表部分元素
1.遍历整个列表
遍历整个列表使得对每个元素进行相同的操作(例如游戏中需要每个界面元素平移相同的距离;包含数字的列表,对每个元素执行相同的统计操作)–>可以用for循环。
#打印所有的魔术师名单
magicians = ['alice','dadong','chou','caroline']
for magician in magicians:
print(magician)
2.深入的研究循环
循环:使计算机能自动完成重复工作
刚开始使用循环时请牢记:对列表中每个元素,都将执行循环指定的步骤,而不管列表包含多少个数据。
使用好的命名习惯:
for cat in cats:
for dog in dogs:
- 在for中执行更多操作
#对每个魔术师打印一条消息,指出他的表演太精彩了!
magicians = ['alice','dadong','chou']
for magician in magicians:
print(magician.title()+", that was a great trick!")
print("I can't wait to see your next trick,"+magician.titil()+".\n")
在for循环之后执行一些操作
需要提高总结性输出或接着执行程序必须完成的其他任务(不缩进)
避免缩进错误3.创建数值列表
数据处理的必要性使用函数range()
for value in range(1,5):
print(value)
#注意!只会打印出1到4!
- 使用range()创建数字列表
numbers = list(range(1,6))
print(numbers)
range()同样可以指定步长:打印1-10之间的偶数
even_numbers = list(range(2,11,2))
print(even_numbers)
创建列表使其数字为1-10的乘方
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
更简单版本
squares = []
for value in range(1,11):
squares.append(value**2)
print(squares)
选择标准:编写清晰易读
- 对数字列表进行简单的统计运算
digits= [1,2,3,4,5,6,77,8,9]
min(digits)
max(digits)
sum(digits)
- 列表解析
squares = [value**2 for value in range(1,11)]
print(squares)
使用列表的一部分
- 切片
和range()相同,python在你指定第二个索引前的元素停止。但是!索引是从0开始的!
- 切片
players = ['charles','eli','martina','michacel','florence']
print(players[0:3])
print(players[2:4])
print(players[:3])#默认从第一个元素开始
print(players[2:])#默认到最后一个元素
print(players[-3:]#负索引,输出列表最后三个元素
- 遍历切片
#遍历前三个队员
players = ['charles','eli','martina','michacel','florence']
print("Here are the first three players on my team:")
for player in players[0:3]:
print(player.title())
- 复制列表
为什么要复制列表:你有一个食物清单,而你的朋友有一个包含你的食物清单的食物清单时。如果想直接:
my_foods = ['pizza','carrot','noddles']
friend_foods = my_foods
#这样是行不通的,指向的是同一个列表
正确做法
my_foods = ['pizza','carrot','noddles']
friend_foods = my_foods[:]#这样复制了整个列表
元组
列表非常适合存储程序运行期间可能变化的数据集。列表是可以修改的,这对处理网站的用户列表或游戏中的角色列表非常重要!
然而,当你需要创建一些列不可修改的元素,就需要元组。
不可变的列表成为元组。- 定义元组
使用()而不是 [ ]
- 定义元组
dimensions = (220,55)
- 遍历元组
dimensions = (220,55)
for dimension in dimensions:
print(dimension)
- 修改元组变量
元组元素不可修改,元组变量可以修改
dimensions = (220,55)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400,55)
print("Modified dimensions:")
for dimension in dimensions:
print(dimension)
PEP 8: python enhancement proposal
python 代码设置指南