1 1 # 3.3.1 使用方法sort() 对列表进行永久性排序
2 2 # 与字母顺序相反的顺序排列列表元素,为此,只需向sort() 方法传递参数reverse=True 。下面的示例将汽车列表按与字母顺序相反的顺序排列:
3 3 cars = ['bmw', 'audi', 'toyota', 'subaru']
4 4 cars.sort(reverse=True)#reversen. 背面;相反;倒退;失败 adj. 反面的;颠倒的;反身的
5 5 print(cars)
6 6 print('*' * 40 + '\n')
7 7 # 使用函数sorted() 对列表进行临时排序
8 8 cars = ['bmw', 'audi', 'toyota', 'subaru']
9 9 print("Here is the original list:")
10 10 print(cars)
11 11 print("\nHere is the sorted list:")
12 12 print(sorted(cars))
13 13 print("\nHere is the original list again:")
14 14 print(cars)
15 15 # 调用函数sorted() 后,列表元素的排列顺序并没有变。
16 16 # 如果你要按与字母顺序相反的顺序显示列表,也可向函数sorted() 传递参数reverse=True
17 17
18 18 # reverse() 不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序
19 19 cars = ['bmw', 'audi', 'toyota', 'subaru']
20 20 print(cars)
21 21 cars.reverse()
22 22 print(cars)
23 23
24 24 #使用函数len() 可快速获悉列表的长度。在下面的示例中,列表包含4个元素,因此其长度为4:
25 25 x_element = len(cars)
26 26 print(x_element)
27 27
28 28 will_go = ['new york','silicon valley','shanghai','sydney','london']
29 29 print(will_go)
30 30 print(sorted(will_go))
31 31 check = 'Check first time'
32 32 print(check,will_go)
33 33 test = sorted(will_go)
34 34 test.reverse()
35 35 print(test)
36 36 check2 = 'Check second time'
37 37 print(check2,will_go)
38 38
39 39 will_go.reverse()
40 40 print(will_go)
41 41 will_go.reverse()
42 42 print(will_go)
43 43 print('*' * 40)
44 44 will_go.sort()
45 45 print(will_go)
46 46 will_go.sort(reverse = True)#True要大写
47 47 print(will_go)
48 48
49 49
50 50 #第四章 操作列表
51 51 magicians = ['alice', 'david', 'carolina']
52 52 for magician in magicians:#此处magician为变量名
53 53 print(magician)
54 54 """首先,我们像第3章那样定义了一个列表(见❶)。接下来,我们定义了一个for 循环(见❷);这行代码让Python从列表magicians 中取出一个名字,并将其存储在变
55 55 量magician 中。最后,我们让Python打印前面存储到变量magician 中的名字(见❸)。这样,对于列表中的每个名字,Python都将重复执行❷处和❸处的代码行。你可以这
56 56 样解读这些代码:对于列表magicians 中的每位魔术师,都将其名字打印出来。"""
57 57 #使用单数和复数式名称,可帮助你判断代码段处理的是单个列表元素还是整个列表。
58 58
59 59 #range 实例
60 60 test = input('>>>')
61 61 print(test)
62 62 l = len(test)
63 63 print(l)
64 64
65 65 r = range(0,l) #[0,3)
66 66 for item in r:
67 67 print(item,test[item])
68 68
69 69 #简化
70 70 test = input('>>>')
71 71 for item in range(0,len(test)):
72 72 print(item,test[item])
73 73
74 74 #随机验证码实例 问题 看视频回顾
75 75 def check_code():
76 76 import random
77 77 checkcode = ''
78 78 for i in range(4):
79 79 current = random.randrange(0,4)
80 80 if current != i:
81 81 temp = chr(random.randint(65,90))
82 82 else:
83 83 temp = random.randint(0,9)
84 84 checkcode += str(temp)
85 85 return checkcode
86 86 code = check_code()
87 87 print(code)
88 88
89 89 #用for循环打印邀请函 遍历
90 90 # # 使用for 循环处理数据是一种对数据集执行整体操作的不错的方式。例如,你可能使用for 循环来初始化游戏——遍历角色列表,将每个角色都显示到屏幕上;再在循环后面添
91 91 # # 加一个不缩进的代码块,在屏幕上绘制所有角色后显示一个Play Now按钮。、
92 92 # magicians = ['alice', 'david', 'carolina']
93 93 # for magician in magicians: #for 语句末尾的冒号告诉Python,下一行是循环的第一行。
94 94 # print(magician.title() + ", that was a great trick!")
95 95 # print("I can't wait to see your next trick, " + magician.title() + ".\n")
96 96 # print("Thank you, everyone. That was a great magic show!")
97 97
98 98 pizzas = ['a','b','c']
99 99 for pizza in pizzas:
100 100 print('I like ' + pizza.title() + ' pizza!')
101 101 print('I really love pizza!')
102 102
103 103 pets = ['dog','cat','rat']
104 104 for pet in pets:
105 105 print("A "+ pet + " would make a great pet")
106 106 print("Any of these animals would make a great pet")
107 107
108 108
109 109 # test = range(0,101,2) #2.7可以直接打印出来 3.*需要从for循环开始表达
110 110 #
111 111 # print(test) #报错
112 112
113 113 # 可使用函数list() 将range() 的结果直接转换为列表。
114 114 numbers = list(range(1,6))
115 115 print(numbers)
116 116 even_numbers = list(range(2,11,2))#使用函数range() 时,还可指定步长。例如,下面的代码打印1~10内的偶数:
117 117 print(even_numbers)
118 118
119 119 # 如何将前10个整数的平方加入到一个列表中:
120 120 squares = []
121 121 for value in range(1,11):
122 122 square = value**2
123 123 squares.append(square)
124 124 print(squares)
125 125
126 126 # 为让这些代码更简洁,可不使用临时变量square ,而直接将每个计算得到的值附加到列表末尾:
127 127 squares = []
128 128 for value in range(1,11):
129 129 squares.append(value**2)
130 130 print(squares)
131 131 # 找出数字列表的最大值、最小值和总和:也适用于包含数百万个数字的列表。
132 132 #>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] #用变量来打印,元素为数值时不需要引号
133 133 #>>> min(digits)
134 134 #0
135 135 #>>> max(digits)
136 136 #9
137 137 #>>> sum(digits)
138 138 #45
139 139
140 140 # 4.3.4 列表解析 #重点
141 141 squares = [value**2 for value in range(1,11)]#定义一个表达式 编写一个for 循环,用于给表达式提供值,此处for无冒号
142 142 print(squares)
143 143
144 144 #练习4-3
145 145 numbers = [v for v in range(1,21)]#使用一个for 循环打印数字1~20(含)。
146 146 print(numbers)
147 147 million = [v for v in range(1,1000001)]
148 148 # print(million)
149 149 min = min(million)
150 150 max = max(million)
151 151 sum = sum(million)
152 152 print(min,max,sum)
153 153
154 154 test = [v for v in range(2,20,2)]
155 155 print(test)
156 156
157 157 test2 = [v for v in range(3,31,3)]
158 158 print(test2)
159 159
160 160 test3 = [v**3 for v in range(1,11)]
161 161 print(test3)
162 162
163 163 #切片
164 164 players = ['charles', 'martina', 'michael', 'florence', 'eli']#均为包含第一个,表示为数学符号如此:[0,6)
165 165 print(players[1:4])#起始索引指定为1 ,并将终止索引指定为4
166 166 print(players[2:])#提取从第3个元素到列表末尾的所有元素,可将起始索引指定为2 ,并省略终止索引:
167 167 print(players[:4])#如果你没有指定第一个索引,Python将自动从列表开头开始:
168 168 print(players[-3:])#要输出名单上的最后三名队员
169 169 # >>>
170 170 # ['martina', 'michael', 'florence']
171 171 # ['michael', 'florence', 'eli']
172 172 # ['charles', 'martina', 'michael', 'florence']
173 173 # ['michael', 'florence', 'eli']
174 174
175 175 #遍历切片
176 176 """在很多情况下,切片都很有用。例如,编写游戏时,你可以在玩家退出游戏时将其最终得分加入到一个列表中。然后,为获取该玩家的三个最高得分,你可以将该列表按降序排
177 177 列,再创建一个只包含前三个得分的切片。处理数据时,可使用切片来进行批量处理;编写Web应用程序时,可使用切片来分页显示信息,并在每页显示数量合适的信息。"""
178 178
179 179 players = ['charles', 'martina', 'michael', 'florence', 'eli']
180 180 print("Here are the first three players on my team:")
181 181 for player in players[:3]:
182 182 print(player.title())
183 183
184 184
185 185 #4.4.3 复制列表
186 186 my_foods = ['pizza', 'falafel', 'carrot cake']
187 187 friend_foods = my_foods[:]
188 188 my_foods.append('cannoli')
189 189 friend_foods.append('ice cream')
190 190 print("My favorite foods are:")
191 191 print(my_foods)
192 192 print("\nMy friend's favorite foods are:")
193 193 print(friend_foods)
194 194
195 195
196 196 #反例
197 197 my_foods = ['pizza', 'falafel', 'carrot cake']
198 198 #这行不通
199 199 friend_foods = my_foods#❶
200 200 my_foods.append('cannoli')
201 201 friend_foods.append('ice cream')
202 202 print("My favorite foods are:")
203 203 print(my_foods)
204 204 print("\nMy friend's favorite foodare:")
205 205 print(friend_foods)
206 206 """这里将my_foods 赋给friend_foods ,而不是将my_foods 的副本存储到friend_foods (见❶)。这种语法实际上是让Python将新变量
207 207 friend_foods 关联到包含在my_foods 中的列表,因此这****重点**两个变量都指向同一个列表******。鉴于此,当我们将'cannoli'
208 208 添加到my_foods 中时,它也将出现在friend_foods 中;同样,虽然'icecream'
209 209 好像只被加入到了friend_foods 中,但它也将出现在这两个列表中。"""
210 210
211 211 #练习4-10 p40
212 212 girls = ['phyllis', 'shiitakeimoto', 'ergou', 'harashima', 'erzi', 'soso', 'dudu']
213 213 print('\""This first three items in the list are:\""')
214 214 print(girls[0:4])
215 215 print('\""Three items from the middle of the list are.\""')
216 216 x = len(girls)
217 217 y = int(x / 2) #int() 向下取整 round() 四舍五入 内置函数 floor() 向下取整math模块函数 ceil() 英文释义:天花板。
218 218 #向上取整 math模块函数 modf() 分别取整数部分和小数部分 math模块函数
219 219 print(y)
220 220 print(girls[y - 1 : y + 2])#原为y + 1 因为不包含冒号右边的数字(闭区间),订正为y + 2
221 221 print('\""The last three items in the list are.\""')
222 222 print(girls[-3:])
223 223
224 224 #4-11
225 225 my_pizzas = ['a','b','c']
226 226 friend_pizzas = my_pizzas[:]
227 227 my_pizzas.append('x')
228 228 friend_pizzas.append('d')
229 229 print("My pizzas are:")
230 230 for z in my_pizzas: #复习for遍历
231 231 print(z)
232 232 print("My friend's pizzas are:")
233 233 for x in friend_pizzas:
234 234 print(x)
235 235 print(my_pizzas,friend_pizzas)
236 236
237 237 #4.5元祖(tuple) Python将不能修改的值称为不可变的 ,而不可变的列表被称为元组 。
238 238 """元组看起来犹如列表,但使用圆括号而不是方括号来标识。定义元组后,就可以使用索引来访问其元素,就像访问列表元素一样。
239 239 例如,如果有一个大小不应改变的矩形,可将其长度和宽度存储在一个元组中,从而确保它们是不能修改的:
240 240 只有1个元素的tuple定义时必须加一个逗号,,来消除歧义:
241 241 'tuple' object does not support item assignment
242 242
243 243 dimensions = (200, 50)
244 244 print("Original dimensions:")
245 245 for dimension in dimensions:
246 246 print(dimension)
247 247 dimensions = (400, 100)
248 248 print("\nModified dimensions:")
249 249 for dimension in dimensions:
250 250 print(dimension)
251 251 如果要修改前述矩形的尺寸,可重新定义整个元组
252 252 """
253 253
254 254 foods = ('ice cream','fried potato','shiitake','apple','peach')
255 255 for food in foods:
256 256 print(food)#循环后最后输出的为peach
257 257
258 258 #foods.insert(0,'pizza')#insert()插入 append()贴上
259 259 print(foods)
260 260 foods = ('beef','sushi','shiitake','apple','peach')
261 261 print(foods)