dict字典
定义
字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 。键必须是唯一的,但值则不必。值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
格式如下所示:d = {key1 : value1, key2 : value2 }
创建
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
or
dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6: 37 }
字典的方法
1.访问:
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
2.修改:
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8 # 更新 Age
print ("dict['Age']: ", dict['Age'])
3. 删除:
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
del dict['Name'] # 删除键 'Name'
dict.clear() # 清空字典
del dict # 删除字典
集合
特性
集合(set)是一个无序的不重复元素序列。可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。
创建
创建格式:
parame = {value01,value02,...}
或者set(value)
方法
1.添加元素:s.add( x )
2.移除元素:s.remove( x ) or s.discard( x )
3.计算集合元素个数:len(s)、
4.清空集合:s.clear()
5.判断元素是否在集合中存在:x in s
判断语句
Python 条件语句是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块。可以通过下图来简单了解条件语句的执行过程:
if 语句:
Python中if语句的一般形式如下所示:
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
如果 "condition_1" 为 True 将执行 "statement_block_1" 块语句
如果 "condition_1" 为False,将判断 "condition_2"
如果"condition_2" 为 True 将执行 "statement_block_2" 块语句
如果 "condition_2" 为False,将执行"statement_block_3"块语句
注意:
1、每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。
2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
3、在Python中没有switch – case语句。
三目表达式
条件为真时的结果 if 判段的条件 else 条件为假时的结果。
编写一个Python程序,输入两个数,比较它们的大小并输出其中较大者。
x = int(input("输入第一个数:"))
y = int(input("输入第二个数:"))
z = int(input("输入第三个数:"))
#三目运算符的第一种写法 p
rint((x if (x>y) else y) if ((x if (x>y) else y)>z) else z)
#三目运算符的第二种写法
a=(x if (x>y) else y) print(a if (a>z) else z)
循环语句
Python中的循环语句有 for 和 while。Python循环语句的控制结构图如下所示:
1.while 循环
while 判断条件:
语句
2、for 语句
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。for循环的一般格式如下:
for <variable> in <sequence>:
<statements>else:
<statements>