|
| 1 | +# 列表的一些其他操作 |
| 2 | +magicians = ['alice', 'david', 'carolina'] |
| 3 | + |
| 4 | +# 遍历列表(缩进是属于循环体;反之,则不是--注意缩进即可) |
| 5 | +for magician in magicians: |
| 6 | + print(magician) |
| 7 | + print("Hello\n") |
| 8 | + |
| 9 | +print("thx everyone") |
| 10 | + |
| 11 | +# 创建数值列表 |
| 12 | +# range(x,y)左闭右开=[x,y) |
| 13 | +for value in range(1, 5): |
| 14 | + print(value) |
| 15 | + |
| 16 | +numbers = list(range(2, 8)) |
| 17 | +print(numbers) |
| 18 | + |
| 19 | +numbers = list(range(1, 7, 2)) |
| 20 | +print(numbers) |
| 21 | + |
| 22 | +squares = [] |
| 23 | +for value in range(1, 11): |
| 24 | + # **2表示平方,这个临时变量也是可以省略的 |
| 25 | + square = value ** 2 |
| 26 | + squares.append(square) |
| 27 | + |
| 28 | +print(squares) |
| 29 | + |
| 30 | +# 获取列表中的最值等 |
| 31 | +digits = list(range(1, 10)) |
| 32 | +print("最小值:" + str(min(digits))) |
| 33 | +print("最大值:" + str(max(digits))) |
| 34 | +print("总数量:" + str(sum(digits))) |
| 35 | + |
| 36 | +# 列表解析 |
| 37 | + |
| 38 | +squares = [value ** 2 for value in range(1, 5)] |
| 39 | +print(squares) |
| 40 | + |
| 41 | +# 判断是否在列表中 |
| 42 | +print(3 in squares) |
| 43 | + |
| 44 | +# 4.4 使用列表的一部分 |
| 45 | +players = ['charles', 'martina', 'michael', 'florence', 'eli'] |
| 46 | +# 同样是左闭右开区间 |
| 47 | +print(players[1:3]) |
| 48 | +# 不指定起始则从头开始 |
| 49 | +print(players[:2]) |
| 50 | +# 同样的末尾不指定则到最后,这里需要注意的是如果起始位置越界了不会报错,只是会返回空的列表 |
| 51 | +print(players[4:]) |
| 52 | +# 还记得之前使用-1来获取最后的一个数吗? |
| 53 | +print(players[-1:]) |
| 54 | + |
| 55 | +# 遍历切片 |
| 56 | +for player in players[1:3]: |
| 57 | + print(player) |
| 58 | + |
| 59 | +# 复制切片 |
| 60 | +persons = players[:] |
| 61 | +print(persons) |
| 62 | +print(persons[0:3]) |
| 63 | + |
| 64 | +persons = players[1:3] |
| 65 | +persons.append('Toms') |
| 66 | +print(persons) |
| 67 | + |
| 68 | +# 4.5元组 |
| 69 | +# 元组不能修改里面的值! |
| 70 | +dimensions = (100, 200) |
| 71 | +print("第一个:" + str(dimensions[0])) |
| 72 | +print("第二个:" + str(dimensions[1])) |
| 73 | + |
| 74 | +# 遍历元组 |
| 75 | +for dimension in dimensions: |
| 76 | + print(dimension) |
| 77 | + |
| 78 | +# 改变元组--直接修改元组的变量 |
| 79 | +print(dimensions) |
| 80 | +dimensions = (200, 400) |
| 81 | +print(dimensions) |
| 82 | + |
| 83 | +# 4.6设置代码格式: Python Enhancement Proposal, PEP |
| 84 | +# PEP 8建议每级缩进都使用四个空格 |
| 85 | +# PEP 8还建议注释的行长都不超过72字符 |
| 86 | +# 要将程序的不同部分分开, 可使用空行 |
0 commit comments