操作列表
1.遍历整个列表
magicians=['alice','david','carolina']
for magician in magicians:
print(magician)
//输出
alice
david
carolina
循环定义magician从magicians中取出元素,再进行打印。
//怎么退出循环
magicians=['alice','david','carolina']
for magician in magicians:
print(magician)
print("good job")
//输出
alice
david
carolina
good job
python中通过缩进来判断程序块,同样,循环也是通过缩进来控制;
创建数值列表
1.range()的使用
for value in range(1,5):
print(value)
range()打印1~4,并不打印5;
2.使用range()来创建数字列表
//使用list()转换成列表
numbers=list(range(1,6))
print(numbers)
//输出
[1,2,3,4,5]
补充:range()可以指定数字间隔
numbers=list(range(2,11,2))
print(numbers)
//输出
[2,4,6,8,10]
函数range()从2开始数,然后不断地加2,直到达到或超过终值11。
3.乘方运算
python中两个星号(**)表示乘方运算。
squares=[]
for value in range(1,11):
squares.append(value**2)
//输出
[1,4,9,16,25,36,49,64,81,100]
如要使用立方只需用**3;
4.计算函数
digits=[1,2,3,4,5,8,10,16]
print(min(digits))
print(max(digits))
print(sum(digits))
//输出
1
16
49
5.列表解析
squares=[value**2 for value in range(1,11)]
print(squares)
//输出
[1,4,9,16,25,36,49,64,81,100]
列表解析将for循环和创建新元素的代码合成为一行,自动附加新元素,填充列表;
使用列表的一部分
1.切片
创建切片,指定要使用的第一个元素和最后一个元素的索引;在到达指定的第二个索引前面的元素后停止。
players=['a','b','c','d']
print(players[0:2])
//输出
['a','b','c']
如果没有指定第一个索引,python从列表开头开始提取;
同样地,如果没有指定第二个索引,python将一直提取到列表末尾;
//如果要提取列表最后三个元素
players=['a','b','c','d','e','f','g','h']
print(player[-3:])
//输出
['f','g','h']
2.遍历切片
//使用for循环来遍历切片
players=['a','b','c','d','e','f','g','h']
for player in players[:3]:
print(player)
//输出
a
b
c
3.复制列表
复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:]);
food=['egg','tomato','potato']
food1=food[:]
print(food)
print(food1)
//输出
['egg','tomato','potato']
['egg','tomato','potato']
//区别
food=['egg','tomato','potato']
food1=food
food1.append('a')
print(food)
print(food1)
food.append('b')
print(food)
print(food1)
//输出
['egg','tomato','potato','a']
['egg','tomato','potato','a']
['egg','tomato','potato','a','b']
['egg','tomato','potato','a','b']
如果不使用[:]对列表进行复制的话,实质上food与food1指向同一个列表,也就是说对其中任何一个操作,另一个也随之改变,因为两者是同一个列表。
元组
元组就是不可变的列表。
定义元组
length=(200,50)
print(length[0])
print(length[1])
//输出
200
50
定义元组与列表的区别:
1.使用圆括号()而不是方括号[]来标识
2.元素不带引号
如果尝试修改元组的元素大小,python会报错。
元组的遍历
元组的遍历与普通列表遍历无异。使用for循环即可实现。
修改元组变量
元组的变量是不能直接单个进行修改的。元组是固定不变的。要想修改元组的元素,只能等效的去修改元组变量。
length=(200,50)
print(length[0])
print(length[1])
length=(250,50)
print(\nlength[0])
print(length[1])
//输出
200
50
250
50
注意:这种修改元组的方式是声明新元组进行覆盖,python允许这样做,因此不会报错。
设置代码格式
提高代码可读性:
1.缩进
PEP8建议每级缩进使用4个空格。
2.行长
PEP8建议注释行长不超过72字符。
一般建议每行不超过80字符。
3.空行
需要使用空行来组织程序文件,但也不能滥用;