7.字典和集合
dict 全称dictionary,使用键值对(key:value)存储数据
在其他语言中一般叫map 与js中的JSON类似
set是无序的,不允许重复
# ---字典
# 定义dict,使用大括号{}
scores = {
'tom': 18,
'jack': 58,
'alice': 60
}
print(scores, type(scores)) # <class 'dict'>
# 获取
print(scores['jack'])
print(scores.get('alice'))
# 添加/修改
scores['lucy'] = 90
scores['jack'] = 80
print(scores)
# 弹出(删除)
print(scores.pop('lucy'))
print(scores)
# 判断在字典中是否存在指定key
print('alice' in scores) # True / False
# 遍历字典
print(scores.keys()) # dict_keys(['tom', 'jack', 'alice'])
print(scores.values()) # dict_values([18, 80, 60])
print(scores.items()) # dict_items([('tom', 18), ('jack', 80), ('alice', 60)])
for k in scores.keys():
print(k, scores[k])
print('=' * 80)
for v in scores.values():
print(v)
print('=' * 80)
for item in scores.items():
print(item[0], item[1])
# 解构赋值
for k, v in scores.items():
print(k, v)
# ----集合set
# 定义set,使用大括号{} 重复值会自动去掉
s = {3, 4, 5, 6, 7, 12, 4}
print(s, type(s))
li = [1, 2, 3, 3, 3, 4, 5, 8]
s = set(li) # 调用set()将list-->set 将list中的重复值去掉
print(s, type(s))
# set添加
s.add(666)
s.add(1) # 自动不会添加重复值
# 删除
s.remove(1)
# 遍历
for i in s:
print(i)
四、函数
函数是实现特定代码段的封装,在需要时可以多次调用
1.内置函数
# 查看函数的帮助信息
help(print)
help(abs)
# 数学运算
print(abs(-5))
print(max(12, 333, 5, 6, 7 - 9))
print(pow(2, 4))
# print(abs('hello')) # 如果参数不对,会报异常TypeError
# 类型转换
print(int('123'))
print(float('123.345'))
print(str(76))
print(bool(5))
# 判断数据类型
a = 12.3
print(isinstance(a, str))
print(isinstance(a, int) or isinstance(a, float))
print(isinstance(a, (int, float)))
2.自定义函数
语法:def 函数名(形参1,形参2,...): 函数体
注意:
- 函数名可以包含数字,字母,下划线,但不能以数字开头下,使用划线相连
- 如果有返回值,使用return关键字
- 定义后的函数不会执行,需要调用后才会执行
def calc(num1, num2): # 必选参数,也称为位置参数
res = num1 + num2
return res
# print(calc(3, 5)) # 调用函数
# print(calc(3)) # 调用函数 TypeError: calc() missing 1 required positional argument: 'num2'
# print(calc(3, 5, 6)) # TypeError: calc() takes 2 positional arguments but 3 were given
# 参数类型检查
def my_abs(x):
# 可以为函数添加文档注释,也称为文档字符串doc string
'''
计算绝对值
:param x: 参数值
:return: 返回x的绝对值
'''
if not isinstance(x, (int, float)):
raise TypeError('参数类型不正确,只能为数值类型') # 抛出异常
if x >= 0:
return x
else:
return -x
# my_abs('aaa')
# print(help(my_abs))
# 默认参数,即有默认值的参数
def my_pow(x, y=2):
if y == 0:
return 1
res = x
for i in range(y - 1):
res *= x
return res
print(my_pow(5, 3))
# print(range(1, 100))
# 可变参数,使用*,表示参数个数是可变的
# 计算多个数字和
def my_sum(x, *y):
print(x)
print(y) # 是个元组tuple
my_sum(3, 5, 6, 7, 8)
# 不建议下边的写法,将必选参数放于前面 ,可选参数放在最后边
def my_sum2(*y, x): # TypeError: my_sum2() missing 1 required keyword-only argument: 'x'
print(x)
print(y)
my_sum2(12, 3, 4, 5, x=9) # 必选参数需要指定参数名
nums = (1, 4, 12,45)
my_sum(4, *nums) # 对于可变参数,可以直接传入list或tuple元组 在参数前加*
# 关键字参数 **,也表示参数是可变的,但传递的是带名称的参数
def f1(x, **y): # 会将传入的参数封装成dict字典
print(x)
print(y)
f1(4, a=5, b=9)
user = {'id':1001,'age':18,'name':'tom'}
# 对于关键字参数 可以直接传入一个dict 只需要在参数前加**
f1(3, id=user['id'], name=user['name'], age=user['age'])
f1(4,**user)
# 命令关键字参数,限制关键字参数的名字,使用*进行分割,*后边表示命名关键字参数
def f2(x, *, name, age):
print(x)
print(name)
print(age)
f2(2, name='alice', age=20)
# 接收任意参数
def f3(*args, **kwargs):
print(args)
print(kwargs)
f3(1, 43, 'aaa', name='alice', age=18)