今天分享的是第四章的要点和部分课后习题的参考代码。
要点:
1、使用for遍历列表(别漏了冒号).
2、避免缩进错误.
3、range()的使用(range()具有三个参数).
4、min()、max()、sum()分别用于找到数字列表的最小值、最大值和计算列表的和.
5、列表解析:列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素.
6、列表切片(参数正数和负数具有不同意义,正数表示从开头开始,负数表示从末尾开始).个人理解列表切片可以理解成子列表.
7、切片(列表)的遍历和复制(直接用赋值号将两个列表相连,两个列表变量指向同一个列表).
8、元组:元组元素无法修改,但是元组变量可以修改.
参考代码:
4-1
pizzas = ['pepperoni', 'onion', 'fish'] for pizza in pizzas: print("I like " + pizza + "pizza.") print("I really love pizza!")
运行结果:
I like pepperonipizza. I like onionpizza. I like fishpizza. [Finished in 0.0s]
4-2
animals = ["pig", "dog", "cat"] for animal in animals: print("A " + animal + "would make a great pet.") print("Any of these animals has four legs")
运行结果:
A pigwould make a great pet. A dogwould make a great pet. A catwould make a great pet. Any of these animals has four legs [Finished in 0.0s]
4-3
for value in range(1,21): print(value)
4-5
values = range(1,1000001) print(min(values)) print(max(values)) print(sum(values))
运行结果:
1 1000000 500000500000 [Finished in 0.1s]
4-6
values = range(1,21,2) for value in values: print(value)运行结果:
1 3 5 7 9 11 13 15 17 19 [Finished in 0.0s]
4-7
values = range(3,31,3) for value in values: print(value)
运行结果:
3 6 9 12 15 18 21 24 27 30 [Finished in 0.0s]
4-8
cubes = [] for value in range(1,11): cube = value**3 cubes.append(cube) print(cubes)
运行结果:
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] [Finished in 0.0s]
4-9
cubes = [value**3 for value in range(1,11)] print(cubes)
运行结果:
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] [Finished in 0.0s]
4-10
pizzas = ['pepperoni', 'onion', 'fish', 'fruit', 'beef' ] print("The first three items in the list are:") print(pizzas[0:3]) print("The middle three items in the list are:") print(pizzas[1:4]) print("The last three items in the list are:") print(pizzas[-3:])
运行结果:
The first three items in the list are: ['pepperoni', 'onion', 'fish'] The middle three items in the list are: ['onion', 'fish', 'fruit'] The last three items in the list are: ['fish', 'fruit', 'beef'] [Finished in 0.0s]
4-11
pizzas = ['pepperoni', 'onion', 'fish', 'fruit', 'beef' ] friend_pizzas = pizzas[:] pizzas.append('spicy') friend_pizzas.append('sweat') print("My favourite pizzas are:") for pizza in pizzas: print(pizza) print("My favourite pizzas are:") for pizza in friend_pizzas: print(pizza)
运行结果:
My favourite pizzas are: pepperoni onion fish fruit beef spicy My favourite pizzas are: pepperoni onion fish fruit beef sweat [Finished in 0.0s]
4-12 略
4-13
foods = ('tomato','potato','fish','rice','pork') for food in foods: print(food) print() foods = ('tomato','noodles','beef','rice','pork') for food in foods: print(food) foods[0]='beef'
运行结果:
tomato potato fish rice pork tomato noodles beef rice pork Traceback (most recent call last): File "/Users/Jhhhha/Desktop/untitled", line 12, in <module> foods[0]='beef' TypeError: 'tuple' object does not support item assignment [Finished in 0.0s with exit code 1]