接上一篇博文!
Python高级数据类型
字典
字典是一个无序的数据集合,使用print函数输出字典时,通常输出的顺序和定义的顺序是不一致的。
xiaoming = {"name": "小明",
"age": 18,
"gender": True,
"height": 1.75,
"weight": 75.5}
字典基本使用
与列表基本一致
xiaoming_dict = {"name": "小明"}
# 1.取值
print(xiaoming_dict["name"])
# 2.增加/删改
# 如果key不存在,会新增键值对
xiaoming_dict["age"] = 18
# 如果key存在,会修改已经存在的键值对
xiaoming_dict["name"] = "小小明"
# 3.删除
xiaoming_dict.pop("name")
print(xiaoming_dict)
一些特有的地方
xiaoming_dict = {"name": "小明",
"age": 18}
# 1.统计键值对数量
print(len(xiaoming_dict))
# 2.合并字典
temp_dict = {"height": 1.75}
# 注意:如果被合并的字典中包含已经存在的键值对,会覆盖原有的键值对
xiaoming_dict.update(temp_dict)
# 3.清空字典
xiaoming_dict.clear()
遍历字典
继续使用for循环迭代遍历。
xiaoming_dict = {"name": "小明",
"qq": "123456",
"phone": "10086"}
# 变量k是每一次循环中,获取到的键值对的key
for k in xiaoming_dict:
print("%s-%s" % (k,xiaoming_dict[k]))
字典遍历常用于描述一些一个对象复杂的数据信息。
# 讲多个字典放在一个列表中,再进行遍历
card_list = [
{"name": "张三",
"qq": "12345",
"phone": "110"},
{"name": "李四",
"qq": "54321",
"phone": "10086"},
]
for card_info in card_list:
print(card_info)
字符串
Python中使用’ '或者" "来创建一个字符串,Python中没有单字符,单个字符也是作为一个字符串使用。
str1 = 'hello'
str2 = "hello"
Python中单引号和双引号基本上没啥区别。
字符串统计操作
hello_str = "hello hello"
# 1.统计字符串长度
print(len(hello_str))
# 2.统计某一个小(子)字符串出现的次数
print(hello_str.count("llo"))
print(hello_str.count("abc"))
# 3.某一个子字符串出现的位置
print(hello_str.index("o"))
# 如果使用index方法传递的子字符串不存在,程序会报错
# print(hello_str.index("abc"))
字符串判断方法
判断字符串中间是否有空格啊,是否有中文数字啊,是否有小数啊等等。
# 1.判断空白字符
space_str = " \t\n\r"
print(space_str.isspace())
# 2.判断字符串中是否只包含数字
# 都不能判断小数
# num_str = "1.1"
# num_str = "\u00b2"
# 中文数字
num_str = "一千零一"
print(num_str)
print(num_str.isdecimal())
print(num_str.isdigit())
print(num_str.isnumeric())
字符串的查找与替换
下面的代码块介绍的很清楚。
hello_str = "hello world"
# 1.判断是否以指定字符串开始
print(hello_str.startswith("Hello"))
# 2.判断是否以指定字符串结束
print(hello_str.endswith("world"))
# 3.查找指定字符串
# index方法同样可以查找指定的字符串在大字符中的索引
print(hello_str.find("llo"))
# index 方法指定的字符串不存在,会报错
# find 方法指定的字符串不存在,会返回-1
print(hello_str.find("abc"))
# 4.替换字符串
# replace 方法执行完成之后,会返回一个新的字符串
# 注意:不会修改原有字符串的内容
print(hello_str.replace("world", "python"))
print(hello_str)
字符串文本对齐
下面有一首诗,如果就像这样输出过来是不是很难看,Python可以通过字符串处理来使他变得更整齐。
# 把下列文字居中对齐
poem = ["\t\n登鹳雀楼",
"王之涣",
"白日依山尽\t\n",
"黄河入海流",
"欲穷千里目",
"更上一层楼"]
加上下面这一串代码,效果就不一样了。
for poem_str in poem:
# 先使用strip 方法去除字符串中的空白字符
# 再使用center 方法居中显示文本
print("|%s|" % poem_str.strip().center(10, " "))
字符串的拆分与拼接
poem_str = "登鹳雀楼\t 王之涣 \t 白日依山尽 \t \n 黄河入海流 \t \t 欲穷千里目 \t 更上一层楼"
print(poem_str)
# 1.拆分字符串
poem_list = poem_str.split()
print(poem_list)
# 2.合并字符串
result = " ".join(poem_list)
print(result)
综合演练
Python遍历字典的列表。
students = [
{"name": "阿土"},
{"name": "小美"}
]
# 在学员列表中搜索指定的姓名
find_name = "张三"
for stu_dict in students:
print(stu_dict)
if stu_dict["name"] == find_name:
print("找到了 %s" % find_name)
# 如果已经找到,应该直接退出循环,而不再遍历后续的元素
break
else:
# 如果希望在搜索列表时,所有的字典检查之后,都没有发现需要搜索的目标
# 还希望得到一个统一的提示
print("抱歉没有找到 %s" % find_name)
print("循环结束")
最后
访问量上百了,终于有五个粉丝了!!!