Python学习第4天
1、多维列表
1.1、创建N*M的多维链表
由于Pyhon没有数据声明的概念创建的过程必须从空白开始创建
例如
# m1=[[0]*3for x in range(3)]创建了3*3的2维列表全是0
# m2=[[0]* 10 for x in range(10)]创建了10*10的2维列表全是0
# m3=[[0]* 12 for x in range(20)]创建了12*20的2维列表全是0
1.2、遍历二维列表
for循环遍历二重循环
for i in range(len(m1)):
for j in range(len(m1[i])):
print(m1[i][j],end=" ")
print()
2、元组
2.1、定义
元组是有序且不可更改的集合。在 Python 中,元组是用圆括号编写的。
和列表大致相同
2.2、方法
count() 返回元组中指定值出现的次数。
index() 在元组中搜索指定的值并返回它被找到的位置。
3、字典
3.1、定义
字典是一个无序、可变和有索引的集合。在 Python 中,字典用花括号编写,拥有键和值。
3.2、创建并打印字典
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
print(thisdict)
3.3、访问字典
3.3.1、通过键来访问
x = thisdict["model"]
3.3.2、通过get()方法
x = thisdict.get("model")
3.4、嵌套字典
创建包含三个字典的字典:
方法1、
myfamily = {
"child1" : {
"name" : "Phoebe Adele",
"year" : 2002
},
"child2" : {
"name" : "Jennifer Katharine",
"year" : 1996
},
"child3" : {
"name" : "Rory John",
"year" : 1999
}
}
方法2、
child1 = {
"name" : "Phoebe Adele",
"year" : 2002
}
child2 = {
"name" : "Jennifer Katharine",
"year" : 1996
}
child3 = {
"name" : "Rory John",
"year" : 1999
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
3.5、dict() 构造函数
也可以使用 dict() 构造函数创建新的字典:
thisdict = dict(brand="Porsche", model="911", year=1963)
# 请注意,关键字不是字符串字面量
# 请注意,使用了等号而不是冒号来赋值
print(thisdict)
3.6、字典方法
4、选择结构
4.1、常见比较
等于:a == b
不等于:a != b
小于:a < b
小于等于:a <= b
大于:a > b
大于等于:a >= b
4.2、If 语句:
a = 66
b = 200
if b > a:
print("b is greater than a")#注意缩进不缩进会报错
4.3、Else
a = 200
b = 66
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")