一、for 循环
1、通过循环顺序打印列表
输入:
bands = ["the beatles", "oasis", "the kinks", "the who"]
for band in bands:
print(f"{band.title()},is my favorite")
print("these are just a few of so many bands")
输出:
The Beatles,is my favorite
Oasis,is my favorite
The Kinks,is my favorite
The Who,is my favorite
these are just a few of so many bands
2、嵌套循环
输入:
bands = ["the beatles", "oasis", "the kinks", "the who"]
heroes = ["the zeli", "efls", "delaiwen"]
for band in bands:
print(f"{band.title()},is my favorite")
for hero in heroes:
print(f"{hero.title()},is also my favorite")
输出:
The Beatles,is my favorite
The Zeli,is also my favorite
Efls,is also my favorite
Delaiwen,is also my favorite
Oasis,is my favorite
The Zeli,is also my favorite
Efls,is also my favorite
Delaiwen,is also my favorite
The Kinks,is my favorite
The Zeli,is also my favorite
Efls,is also my favorite
Delaiwen,is also my favorite
The Who,is my favorite
The Zeli,is also my favorite
Efls,is also my favorite
Delaiwen,is also my favorite
注意:
(1)是否包含在循环内,取决于是否缩进
二、range() 的使用:可输入三个数,第一个数是第一顺位的数字,第二个数是生成数的个数加1,第三个数是各个数之间的间隔,若没有第三个数,则默认间隔是1;
1、创建数字列表
(1)输入:
squares = list(range(1, 10))
print(squares)
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
(2)输入:
squares = list([])
for value in range(1, 11, 2):
squares.append(value**2)
print(squares)
输出:
[1, 9, 25, 49, 81]
还可以这么写:
输入:
squares = list(value**2 for value in range(1, 11, 2))
print(squares)
输出:
[1, 9, 25, 49, 81]
2、对数字列表进行简单的统计计算
输入:
squares = list(range(1, 10))
print(min(squares))
print(max(squares))
print(sum(squares))
输出:
1
9
45
三、对列表中的一部分数据进行操作
1、切片:在列表名后使用 [起点元素位置,终点元素位置+1,步长],元素位置从0开始,若没有起点元素位置声明,则默认从表头(第一个元素编号0 开始;若没有终点元素位置声明,则默认终止于表尾
eg:
输入:
band = ["oasis", "the beatles", "eagles", "the who", "the kinks"]
print(band[1:3])
print(band[0])
输出:
['the beatles', 'eagles']
oasis
2、复制列表:
band = ["oasis", "the beatles", "eagles", "the who", "the kinks"]
bands = band[:]
print(bands)
列表生成式 :
输入:
lst = [i for i in range(1, 11)]
print(lst)
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
三、元组:不可变序列,不能增删改
元组变量不可修改,不可添加或者删除,其余使用与列表类似,但若元组中只有一个元素后面要有,。元组的定义用(),空元组用
a = tuple()
表示