Python Class 4:操作列表

目录

4.1 遍历列表

4.2 避免缩进错误

4.3 创建数值列表

1.range()

2.创建数字列表

3.统计计算

4.列表解析

4.4 使用列表

1.切片

2.遍历切片

3.复制列表

4.5 元组

1.定义

2.遍历元组元素

3.修改元组变量

4.6 代码格式

1.缩进

2.行长

3.其他

作业


4.1 遍历列表

当列表过长导致逐个输出困难时,可使用for循环处理问题。

family=['tian','han','ben','pao']
for name in family:
	print(name)    #循环内必须缩进
tian
han
ben
Pao

for循环可对每个元素执行操作

>>> family=['tian','han','ben','pao']
>>> for name in family:
...  print(name.title()+" is my homie")
...
Tian is my homie
Han is my homie
Ben is my homie
Pao is my homie

在for循环后,没有缩进的代码只执行一次。

4.2 避免缩进错误

Python根据缩进来判断代码行与前一个代码行的关系。for循环的标准是

for ...in ... :

  ......

  ......

4.3 创建数值列表

列表适用于存储数字。

1.range()

>>> for value in range(1,5):
...  print(value)
...
1
2
3
4

range(a,b),从a开始,到b-1为止

2.创建数字列表

可使用list()将range()结果转换为列表

>>> numbers=list(range(1,6))
>>> numbers
[1, 2, 3, 4, 5]

range()还可指定步长,例如若需打印1-10内的偶数,则

>>> even_numbers=list(range(2,11,2))
>>> even_numbers
[2, 4, 6, 8, 10]

在python用**表示平方

>>> squares=[]
>>> for value in range(1,11):
...  square=value**2
...  squares.append(square)
...
>>> print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

3.统计计算

用几个列表专用函数如下:

>>> digits=[1,2,3,4,5,6,7,8,9,0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45

4.列表解析

列表解析将for循环和创建新元素的代码合成一行,并自动附加新元素。

>>> squares=[value**2 for value in range(1,11)]
>>> print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

描述性列表名=[表达式(生成要存储的值)  for循环(为了给表达式提供值)]

4.4 使用列表

1.切片

切片即处理列表的部分元素。指定第一个和最后一个元素索引,python对第一个元素和最后一个元素前的一个元素进行处理。

>>> players=['charles','martina','michael','florence','eli']
>>> print(players[0:3])
['charles', 'martina', 'michael']

若没有指定起始索引,将从列表开头处理。

>>> print(players[:4])
['charles', 'martina', 'michael', 'florence']

若没有指定终止索引,将处理到持续列表末尾。

>>> print(players[1:])
['martina', 'michael', 'florence', 'eli']

2.遍历切片

在for循环中使用切片可进行遍历。

>>> for player in players[:3]:
...  print(player)
...
charles
martina
michael

3.复制列表

首先创建一个包含列表所有内容的切片,可同时省略起始与终止索引。

>>> my_foods=['pizza','falafel','carrot cake']
>>> friend_foods=my_foods[:]
>>> print(my_foods)
['pizza', 'falafel', 'carrot cake']
>>> print(friend_foods)
['pizza', 'falafel', 'carrot cake']

注意:复制后的列表只是内容与被复制的列表相同,但这是两个不同列表。

4.5 元组

1.定义

不可变的列表称为元组,使用圆括号标记。

>>> dimensions=(200,50)
>>> dimensions[0]
200
>>> dimensions[1]
50

若对元组中元素改变时:

>>> dimensions[0]=100
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

2.遍历元组元素

元组也可以像列表一样用for循环遍历。

>>> for dimension in dimensions:
...  print(dimension)
...
200
50

3.修改元组变量

尽管无法修改元组值,但可以通过重新定义元组,修改元组值。

>>> dimensions=(200,50)
>>> dimensions
(200, 50)
>>> dimensions=(100,20)
>>> dimensions
(100, 20)

4.6 代码格式

1.缩进

每级缩进使用四个空格

2.行长

行长不超过80字符

3.其他

PEP 8有一些格式要求:https://python.org/dev/peps/pep-0008/

作业

1.想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用for 循环将每种比萨的名称都打印出来。

修改这个for 循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称。对于每种比萨,都显示一行输出

在程序末尾添加一行代码,它不在for 循环中,指出你有多喜欢比萨。

>>> pizza=["red pizza","blue pizze","black pizze"]
>>> for kind in pizza:
...  print(kind)
...
red pizza
blue pizze
black pizze

>>> for kind in pizza:
...  print("I like eat "+ kind)
...
I like eat red pizza
I like eat blue pizze
I like eat black pizze

pizza=["red pizza","blue pizza","black pizza"]
for kind in pizza:
	print("i like eat "+kind)
print("i like pizza")
i like eat red pizza
i like eat blue pizza
i like eat black pizza
i like pizza

2.想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用for 循环将每种动物的名称都打印出来。

修改这个程序,使其针对每种动物都打印一个句子

在程序末尾添加一行代码,指出这些动物的共同之处
答:略
3. :使用一个 for 循环打印数字 1~20 (含)
>>> for value in range(1,21):
...  print(value)
...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
4.创建一个列表,其中包含数字 1~1 000 000 ,再使用一个 for 循环将这些数字打印出来(如果输出的时间太长,按 Ctrl+ C 停止输出,或关闭输出窗口)。
numbers=range(1,1000001)
for number in numbers:
 print(number)

5.创建一个列表,其中包含数字1~1 000 000,再使用min() max() 核实该列表确实是从1开始,到1 000 000结束的。另外,对这个列表 调用函数sum() ,看看Python将一百万个数字相加需要多长时间。

>>> min(numbers)
1
>>> max(numbers)
1000000
>>> sum(numbers)
500000500000
6.通过给函数 range() 指定第三个参数来创建一个列表,其中包含 1~20 的奇数;再使用一个 for 循环将这些数字都打印出来。
>>> numbers=range(1,21,2)
>>> for number in numbers:
...  print(number)
...
1
3
5
7
9
11
13
15
17
19

7.创建一个列表,其中包含3~30内能被3整除的数字;再使用一个for 循环将这个列表中的数字都打印出来。

>>> numbers=range(3,31,3)
>>> for number in numbers:
...  print(number)
...
3
6
9
12
15
18
21
24
27
30

8.请创建一个列表,其中包含前10个整数(即1~10)的立方,再使用一个for 循环将这些立方数都打印出来。

>>> number=[]
>>> for number in range(1,11):
...  number=number**3
...  print(number)
...
1
8
27
64
125
216
343
512
729
1000
9.使用列表解析生成一个列表,其中包含前 10 个整数的立方。
>>> numbers=[number**3 for number in range(1,11)]
>>>
>>> numbers
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

10.选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。

打印消息“Thefirst threeitems in thelistare:”,再使用切片来打印列表的前三个元素。

打印消息“Threeitems fromthe middle ofthelistare:”,再使用切片来打印列表中间的三个元素。

打印消息“Thelast threeitems in thelistare:”,再使用切片来打印列表末尾的三个元素。

>>> numbers
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

>>> print("Thefirst threeitems in thelistare: "+str(numbers[0:3]))
Thefirst threeitems in thelistare: [1, 8, 27]

>>> print("Three items from the middle of thelist are: "+str(numbers[3:6]))
Three items from the middle of thelist are: [64, 125, 216]

>>> print("Thelast three items in the list are: "+str(numbers[7:10]))
Thelast three items in the list are: [512, 729, 1000]

11.在你为完成练习4-1而编写的程序中,创建比萨列表的副本,并将其存储到变量friend_pizzas 中,再完成如下任务。在原来的比萨列表中添加一种比萨。

在列表friend_pizzas 中添加另一种比萨。

核实你有两个不同的列表。为此,打印消息“My favorite pizzasare:”,再使用一个for 循环来打印第一个列表;打印消息“My friend's favorite pizzasare:”,再使用一 个for 循环来打印第二个列表。核实新增的比萨被添加到了正确的列表中。

>>> pizza=['red pizza', 'blue pizza', 'black pizza']
>>> friend_pizza=pizza[:]
>>> pizza.append("yellow pizza")
>>> friend_pizza.append("green pizza")
>>> for kind in pizza:
...  print(kind)
...
red pizza
blue pizza
black pizza
yellow pizza
>>> for friend_kind in friend_pizza:
...  print(friend_kind)
...
red pizza
blue pizza
black pizza
green pizza

12.有一家自助式餐馆,只提供五种简单的食品。请想出五种简单的食品,并将其存储在一个元组中。

使用一个for 循环将该餐馆提供的五种食品都打印出来。

尝试修改其中的一个元素,核实Python确实会拒绝你这样做。

>>> foods=("rice","noodles","dumplings","tomato","potato")
>>> for food in foods:
...  print(food)
...
rice
noodles
dumplings
tomato
potato

>>> foods[1]="cafe"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值