DataWhale—Python Task3
1. Dict字典
1) 定义
Dict字典是另一种可变容器模型,且可存储任意类型对象。
2) 创建
字典的每个键值key=>value对用冒号:分割,每个对之间用逗号,分割,整个字典包括在花括号{}中 ,格式如下所示:
d = {key1 : value1,
key2 : value2 }
键必须是唯一的,但值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
一个简单的字典实例:
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
也可如此创建字典:
dict1 = {'abc'}
dict1 = {'abc': 456}
dict2 = { 'abc': 123,
98.6: 37 };
创建一个空字典
dict1{}
3) 字典的方法
访问字典中的值
把相应的键放入到方括号中,如下实例:
parameters["W1"]
print('parameters["W1"]:',parameters["W1"])
修改字典
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:
parameters["W1"] = 0 # 更新W1
parameters["W3"] = W3 # 添加信息
删除字典元素
能删单一的元素也能清空字典,清空只需一项操作。显示删除一个字典用del命令,如下实例:
del parameters["W3"] # 删除字典中一个元素
parameters.pop("W3") # 删除字典中一个元素
parameters.clear() # 清空字典
del parameters # 删除字典
计算字典元素个数
>>>len(parameters) #计算字典parameters中元素个数
4
2. 集合
1) 特性
集合Set是一个无序的不重复元素序列。
可以使用大括号{ }或者set()函数创建集合,注意:创建一个空集合必须用set()而不是{ },因为{ } 是用来创建一个空字典。
2) 创建
set1 = {'W1','W2','b1','b2'...}
set2()
3) 方法
添加元素
>>>set2.add('W3')
>>>print(set2)
{'W3'} # 向字典set2中添加元素W3
>>>set2.update({1,3})
>>>print(set2)
{1,3,'W3'} # 向字典中添加元素1,3
移除元素
>>>set2.remove({1,3})
>>>print(set2)
{'W3'} #将元素1,3从集合set2中移除,如果元素不存在,则会发生错误
>>>set2.discard({1,3})
>>>print(set2)
{'W3'} #将元素1,3从集合set2中移除,如果元素不存在,不会发生错误
计算集合元素个数
>>>len(set1) #计算集合set1中元素个数
3
3. 判断语句(要求掌握多条件判断)
if else语句,满足条件后执行后边的语句
if expression
expr_true_suite
else
expr_false_suite
如果在判断语句中,需要更细的粒度,则使用elif语句或者条件嵌套
if expression
expr_true_suite
elif expression2
expr_ture_suite
elif expression
expr_ture_suite
...
else
实例如下
# if else elif practice
x = int(input('test score:'))
if 90 < x < 100:
print('the grade is A')
elif 70 <= x < 89:
print('the grade is B')
elif 60 <= x < 69:
print('the grade is C')
elif 0 <= x < 59:
print('the grade is D')
else:
print('invalid score')
# Find the solution of a quadratic equation
import math
a,b,c = eval(input('Enter three parameters:'))
t = b * b - 4 * a * c
if t < 0:
print('invalid parameters')
elif t == 0:
y = -b/(2 * a)
print('y = {:.1f}'.format(y))
else:
y1 = (-b + math.sqrt(t))/(2 * a)
y2 = (-b - math.sqrt(t))/(2 * a)
print('y1 = {:.1f},y2 = {:.1f}'.format(y1,y2))
4. 三元表达式
实例如下
# Generate a Fibonacci sequence
def fib(n):
if n == 0 or n == 1:
return
else:
return fib(n-1) + fib(n-2)
#通过递归的方法生成斐波那契数列
参考文献
link.https://www.runoob.com/python3/python3-dictionary.html
link.https://www.icourse163.org/course/NJU-1001571005
本文深入探讨了Python中的字典和集合数据结构的创建、使用及操作方法,同时讲解了条件语句的运用,包括多条件判断和三元表达式的实战应用。
195

被折叠的 条评论
为什么被折叠?



