1.元组
python的容器包括元组、列表、字典和集合
以下是元组部分
1.1常规元组操作
# 元组内的数据不可更改
# null
tuple1=tuple()
# 列表变为元组
tuple1=tuple([1,2,3])
print(tuple1)
tuple2=tuple('hello')
print(tuple2)
tuple3=(1,'zs',True)
print(tuple3)
用()定义元组时,只有一个数据时需要"," tuple1=(1,) print(tuple1)元组的值不可变的原因:对应的地址不会变,故可以改变元组中的一个列表元素中的内容
tuple1=(1,4,[1,4,3])
tuple1[-1][0]=10
print(tuple1)
1.2组包,拆包
# 组包
a,b=10,20
c=b,a
print(type(c),c)
# 拆包
a,b=c
print(a,b)
2.字典
2.1基础运用
以下是字典的常规用法,包括了定义,添加,修改,字典中的列表添加,删除和清空
dict1={'name':'xiaoMing','age':18,'like':['抽烟','喝酒','烫头']}
print(dict1)
dict1['sex']='男'
print(dict1)
dict1['age']='20'
print(dict1)
dict1['like'].append('下馆子')
print(dict1)
del dict1['sex']
dict1.pop('age')
print(dict1)
# dict1['like'].remove('抽烟')
dict1['like'].pop(0)
print(dict1)
dict1.clear()
print(dict1)
字典的创建和数据整改完成后,就需要对字典内的数据进行提取了
dict1={'name':'xiaoMing','age':18,'like':['抽烟','喝酒','烫头']}
print(dict1["name"])
print(dict1.get("name"))
print(dict1.get('sex'))
for k in dict1.keys():
print(k)
for v in dict1.values():
print(v)
2.2字典拆包
def greet(greeting, name):
print(f"{greeting}, {name}!")
# 使用 * 解包列表
names = ["Hello", "World"]
greet(*names) # 这里的 *names 相当于 greet("Hello", "World")
# 使用 ** 解包字典
person = {"greeting": "Hi", "name": "Alice"}
greet(**person) # 这里的 **person 相当于 greet(greeting="Hi", name="Alice")
3.python函数
python中函数的创建使用了def关键词,其语法为:
函数定义
def 函数名():
函数体
函数调用
函数名()
3.1函数的嵌套使用
def fun1():
print(1)
def fun2():
fun1()
print(2)
# 调用
fun2()
输出为:1
2
3.2全局变量与局部变量
a,b=10,20
def fun1():
b=30
print(a,b)
def fun2():
print(a,b)
# 调用
fun1()
fun2()
3.3匿名函数
Lambda表达式在Python中是一种特殊的函数形式,也被称为匿名函数。它可以在一行代码中定义函数并立即调用,非常适合用于定义简单的、一次性的函数对象。
# 简单函数运算
fun1=lambda a,b:a*b
print(fun1(1,2))
print(fun1(2,3))
# 使用lambda在字典中取值
fun2=lambda a:a.get('age')
dict1={'name':'zs','age':'18'}
print(fun2(dict1))