day05
今日内容
- 字典
作业题讲解和变换
见代码文件
内容回顾和补充
-
int
- py2/py3区别
- 除法
- 强制轮换 :
- int(“字符串”) [重要]
- int(bool)
-
bool
-
强制转换:
- bool(数字) -> bool(1)... bool(0)
bool(字符串) -> bool(“xxx”)... bool(“”)
bool(列表) -> bool([sf,sdf,d])... bool([])
bool(元组) -> bool((1,2,3,))... bool((,))
- bool(数字) -> bool(1)... bool(0)
-
0/“”转换是False
v1 = bool(0) v2 = bool("") v3 = bool([]) v4 = bool(()) print(v1, v2, v3, v4) # False
-
-
str
- 独有功能:upper/lower/splist/strip/replace/isdigti/startswith/endswith/format/join/encode
- 公共功能:
- len
- 索引
- 切片
- 步长
- for循环
- 删除[无]
- 更新[无]
- 强制转换:
- str(999) # “999”
- str(True) # “True”
- str([“唐开发”,”李中伟“]) # “[“唐开发”,”李中伟“]” --> v2 = “”.join([“唐开发”,”李中伟“]) # “唐开发李中伟”
- str((“唐开发”,”李中伟“)) 和列表一样
-
list
独有功能:append/insert/pop/remove/clear/extend
- 公共功能:
- len
- 索引
- 切片
- 步长
- for循环
- 删除
- 更新
-
强制转换:
- list(“adfsfsfafasf”)
v1 = list(“adfsfsfafasf”) print(v1)
- list((11,22,33,44)) 元组转列表
v1 = list((11,22,33,44)) print(v1)
- len
-
tuple
独有功能: [无]
- 公共功能:
- len
- 索引
- 切片
- 步长
- for循环
- 删除[无]
- 更新[无]
-
强制转换:
- tuple(“adfsfsfafasf”)
v1 = tuple(“adfsfsfafasf”) print(v1)
-
tuple([11,22,33])
v1 = list([11,22,33,44]) print(v1)
- len
-
总结
-
常见的类型转换
# 字符串转数字 # 数字转字符串 # 列表转元组 # 元组转列表 # 其他转bool时, 只有: 0 “” [] ()
# 练习题 nums = [11, 22, 33, 44] for i in range(0,len(nums)): nums[i] = str(nums[i]) nums_str = "_".join(nums) print(nums_str) # 1. "".join([元素必须是字符串,元素是字符串,])
-
今日内容
1.字典
帮助用户云表示一个事物的信息(事物是有多个属性)。
info = {"name":"刘伟达","age":18,"gender":"男","hobby":"同桌"} # 键值
# 请输入出:我今天点 %s,他的年龄是%s,性别是%s,他喜欢他的%s;
基本格式
data = {键:值,键:值,键:值,键:值}
# 练习题
userinfo = {"username":"alex","password":"oldboy"}
user = input("请输入用户:")
pwd = input("请输入密码:")
if userinfo["username"] == user and userinfo["password"] == pwd:
print("登录成功")
else:
print("用户名密码错误")
-
独有功能
info = {"name":"刘伟达","age":18,"gender":"男","hobby":"同桌"}
-
keys , 获取字典所有键
# for item in info.keys(): # print(item)
-
values, 获取字典所有值
# for item in info.values(): # print(item)
-
items ,获取字典所有键和值
for v1, v2 in info.items(): print(v1, v2)
- 公共功能我
-
len
info = {"name": "刘伟达", "age": 18, "gender": "男", "hobby": "同桌"} print(len(info))
-
索引
info = {"name": "刘伟达", "age": 18, "gender": "男", "hobby": "同桌"} info["name"] info["age"]
切片【无】
步长 【无】
-
for
info = {"name": "刘伟达", "age": 18, "gender": "男", "hobby": "同桌"} for item in info.keys(): print(item) for item in info.values(): print(item) for v1, v2 in info.items(): print(v1, v2)
-
修改(存在修改/不存在增加)
# 改值 info = {"name": "刘伟达", "age": 18, "gender": "男", "hobby": "同桌"} info["age"] = 19 print(info) # 改键 # 删除后再增加 def info["hobby"] info["xxxxx"] = "x1"
-
删除
info = {"name": "刘伟达", "age": 18, "gender": "男", "hobby": "同桌"} del info["name"] print(info)
-
重点
- int
- bool
- str
- list
- tuple
- dict