# python_homework_week07 **Repository Path**: ifishes/python_homework_week07 ## Basic Information - **Project Name**: python_homework_week07 - **Description**: No description available - **Primary Language**: Python - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-11-02 - **Last Updated**: 2021-01-13 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # python_homework_week07 #### 作业要求 1、总结关于字典、集合的所有方法 请自行练习关于字典(dict)以及集合(set)相关内容,并做总结。 2、猜数字练习 课上已演示过,请自行再次练习 3、课本代码练习(关于第三章p95~p144的代码) 4、字典查询练习: Azure API 提供一张含有>=3张脸(3个以上faceid)的图片,先用json()获取内容(results),在用数据结构查询的方式查找到:眼镜、肤色、微笑指数、头发颜色、年龄、性别这几项数据,并分别存进变量/自定义数据结构(如字典等)当中。 --- --- ## 一、字典、集合的方法总结 ### Python 字典(Dictionary) 字典是另一种可变容器模型,且可存储任意类型对象。 - 字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ``` d = {key1 : value1, key2 : value2 } ``` - 键一般是唯一的,如果重复最后的一个键值对会替换前面的,值不需要唯一。 ``` >>> dict = {'a': 1, 'b': 2, 'b': '3'} >>> dict['b'] '3' >>> dict {'a': 1, 'b': '3'} ``` - 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。 一个简单的字典实例: ``` dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} ``` - 也可如此创建字典: ``` dict1 = { 'abc': 456 } dict2 = { 'abc': 123, 98.6: 37 } ``` --- #### 1. 访问字典里的值 - 把相应的键放入熟悉的方括弧,如下实例: ``` dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print "dict['Name']: ", dict['Name'] print "dict['Age']: ", dict['Age'] ``` 以上输出结果: ``` dict['Name']: Zara dict['Age']: 7 ``` #### 2. 修改字典 - 向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例: ``` dict = {'Name': 'Bela', 'Age' : '7', 'Class' : 'First'} dict['Age'] = 8 # 更新 dict['School'] = "RUNOOB" # 添加 print "dict['Age']:", dict['Age'] print "dict['School']: ", dict['School'] ``` 以上实例输出结果: ``` dict['Age']: 8 dict['School']: RUNOOB ``` #### 3.删除字典元素 - 能删单一的元素也能清空字典,清空只需一项操作。 显示删除一个字典用del命令,如下实例: ``` dict = {'Name': 'Bela', 'Age' : '7', 'Class' : 'First'} del dict['Name'] # 删除键是'Name'的条目 dict.clear() # 清空字典所有条目 del dict # 删除字典 print "dict[Name]:"",dict[Name] print "dict['Age']: ", dict['Age'] ``` 但这会引发一个异常,因为用del后字典不再存在 输出结果如下: ``` dict['Age']: Traceback (most recent call last): File "test.py", line 8, in print "dict['Age']: ", dict['Age'] TypeError: 'type' object is unsubscriptable ``` #### 4.字典键的特性 字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。 - 两个重要的点需要记住: 1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例: ``` dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'} print "dict['Name']: ", dict['Name'] ``` 输出结果: ``` dict['Name']: Manni ``` 2)键必须不可变,所以可以用数字,字符串或元组充当,所以用列表就不行,如下实例: ``` dict = {['Name']: 'Zara', 'Age': 7} print "dict['Name']: ", dict['Name'] ``` 输出结果: ``` Traceback (most recent call last): File "test.py", line 3, in dict = {['Name']: 'Zara', 'Age': 7} TypeError: list objects are unhashable ``` #### 5.字典内置函数&方法 - Python字典包含了以下内置函数: |序号|函数|描述| |---|---|---| |1| cmp(dict1, dict2)|比较两个字典元素| |2|len(dict)|计算字典元素个数,即键的总数| |3|str(dict)|输出字典可打印的字符串表示| |4|type(variable)|返回输入的变量类型,如果变量是字典就返回字典类型| - Python字典包含了以下内置方法: |序号|函数|描述| |---|---|---| |1|dict.clear()|删除字典内所有元素| |2|dict.copy()|返回一个字典的浅复制| |3| dict.fromkeys(seq[, val])|创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值| |4| dict.get(key, default=None)|返回指定键的值,如果值不在字典中返回default值| |5| dict.has_key(key)|如果键在字典dict里返回true,否则返回false| |6| dict.items()|以列表返回可遍历的(键, 值) 元组数组| |7| dict.keys()|以列表返回一个字典所有的键| |8|dict.setdefault(key, default=None)|和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default| |9| dict.update(dict2)|把字典dict2的键/值对更新到dict里| |10|dict.values()|以列表返回字典中的所有值| |11|pop(key[,default])|删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值| |12|popitem()|返回并删除字典中的最后一对键和值| --- ### 集合 - 集合(set)是一个无序的不重复元素序列。 可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。 创建格式: ``` parame = {value01,value02,...} 或者 set(value) ``` 实例演示: ``` >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} >>> print(basket) # 这里演示的是去重功能 {'orange', 'banana', 'pear', 'apple'} >>> 'orange' in basket # 快速判断元素是否在集合内 True >>> 'crabgrass' in basket False >>> # 下面展示两个集合间的运算. ... >>> a = set('abracadabra') >>> b = set('alacazam') >>> a {'a', 'r', 'b', 'c', 'd'} >>> a - b # 集合a中包含而集合b中不包含的元素 {'r', 'd', 'b'} >>> a | b # 集合a或b中包含的所有元素 {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} >>> a & b # 集合a和b中都包含了的元素 {'a', 'c'} >>> a ^ b # 不同时包含于a和b的元素 {'r', 'd', 'b', 'm', 'z', 'l'} ``` #### 集合的基本操作 ##### 1.添加元素 - 语法格式 ``` s.add( x ) ``` 示例: ``` >>> thisset = set(("Google", "Runoob", "Taobao")) >>> thisset.add("Facebook") >>> print(thisset) {'Taobao', 'Facebook', 'Google', 'Runoob'} ``` - 还有一个方法,也可以添加元素,且参数可以是列表,元组,字典等,语法格式如下: ``` s.update( x ) ``` x 可以有多个,用逗号分开。 ``` >>> thisset = set(("Google", "Runoob", "Taobao")) >>> thisset.update({1,3}) >>> print(thisset) {1, 3, 'Google', 'Taobao', 'Runoob'} >>> thisset.update([1,4],[5,6]) >>> print(thisset) {1, 3, 4, 5, 6, 'Google', 'Taobao', 'Runoob'} >>> ``` ##### 2.移除元素 语法格式如下: ``` s.remove(x) ``` - 将元素 x 从集合 s 中移除,如果元素不存在,则会发生错误。 ``` >>> thisset = set(("Google", "Runoob", "Taobao")) >>> thisset.remove("Taobao") >>> print(thisset) {'Google', 'Runoob'} >>> thisset.remove("Facebook") # 不存在会发生错误 Traceback (most recent call last): File "", line 1, in KeyError: 'Facebook' >>> ``` - 此外还有一个方法也是移除集合中的元素,且如果元素不存在,不会发生错误。格式如下所示: ``` s.discard( x ) ``` - 我们也可以设置**随机**删除集合中的一个元素,语法格式如下: ``` s.pop() ``` ``` thisset = set(("Google", "Runoob", "Taobao", "Facebook")) x = thisset.pop() print(x) ``` 输出结果: ``` $ python3 test.py Runoob ``` ##### 3.计算集合元素个数 语法格式如下: ``` len(s) ``` - 计算集合 s 元素个数。 ``` >>> thisset = set(("Google", "Runoob", "Taobao")) >>> len(thisset) 3 ``` ##### 4.清空集合 语法格式如下: ``` s.clear() ``` - 清空集合 s。 ``` >>> thisset = set(("Google", "Runoob", "Taobao")) >>> thisset.clear() >>> print(thisset) set() ``` ##### 5.判断元素是否在集合中存在 语法格式如下: ``` x in s ``` - 判断元素 x 是否在集合 s 中,存在返回 True,不存在返回 False。 ``` >>> thisset = set(("Google", "Runoob", "Taobao")) >>> "Runoob" in thisset True >>> "Facebook" in thisset False >>> ``` - 集合内置方法完整列表 |方法|描述| |---|---| |add()| 为集合添加元素| |clear()| 移除集合中的所有元素| |copy()| 拷贝一个集合| |difference()| 返回多个集合的差集| |difference_update()| 移除集合中的元素,该元素在指定的集合也存在。| |discard()| 删除集合中指定的元素| |intersection()| 返回集合的交集| |intersection_update()| 返回集合的交集。| |isdisjoint()| 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。| |issubset()| 判断指定集合是否为该方法参数集合的子集。| |issuperset()| 判断该方法的参数集合是否为指定集合的子集| |pop()| 随机移除元素| |remove()| 移除指定元素| |symmetric_difference()| 返回两个集合中不重复的元素集合。| |symmetric_difference_update()| 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。| |union()| 返回两个集合的并集| |update()| 给集合添加元素| --- ## 二、猜数字python练习 [猜数字.py](https://gitee.com/ifishes/python_homework_week07/blob/master/%E7%8C%9C%E6%95%B0%E5%AD%97.py) ## 三、课本代码练习 P113 练习代码: ``` vowels = ['a','e','i','o','u'] word = input("provide a word to search for vowels:") found = {} found['a'] = 0 found['e'] = 0 found['i'] = 0 found['o'] = 0 found['u'] = 0 for letter in word: if letter in vowels: found[letter]+=1 for k,v in sorted(found.items()): print(k,'was found',v,'time(s)') ``` 输出结果如下: ``` provide a word to search for vowels:georgia on my mind a was found 1 time(s) e was found 1 time(s) i was found 2 time(s) o was found 2 time(s) u was found 0 time(s) ``` P129 练习代码: ``` vowels=set('aeiou') #将列表改成了集合 word=input('请输入你想搜索元音的单词:') found=vowels.intersection(set(word)) #这里比初代版本删减了5行代码,更为简洁 for vowels in found: print(vowels) ``` 输出结果如下: ``` 请输入你想搜索元音的单词:georgia on my mind o a i e ``` P131 联系代码: ``` vowels = set('aeiou') word = input("Provide a word to search for vowels: ") found = vowels.intersection(set(word)) for vowel in found: print(vowel) ``` 输出结果如下: ``` Provide a word to search for vowels: sitting here in silence i e ``` --- ## 四、字典查询练习: ``` # A-1 面部检测 import requests import json # set to your own subscription key value subscription_key = "f212f71663134b73bdec4a5a9aece2f0" assert subscription_key face_api_url = 'https://face-ozl.cognitiveservices.azure.com/face/v1.0/detect' # 请求正文 image_url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1604314497260&di=d6a42d6df450d9d56faebc05e06aa7fc&imgtype=0&src=http%3A%2F%2Fi2.hdslb.com%2Fbfs%2Farchive%2F763746c58023cf36f7f1b5a1c05857e03f2e0946.jpg' # 整一张有3张或以上人脸的图 subscription_key = "4f253843772f42e89e959977f6149561" headers = {'Ocp-Apim-Subscription-Key': subscription_key} # 请求参数 params = { 'returnFaceId': 'true', 'returnFaceLandmarks': 'false', # 选择model 'recognitionModel':'recognition_03',#此参数需与facelist参数一致 'detectionModel':'detection_01', # 可选参数,请仔细阅读API文档 'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise', } response = requests.post(face_api_url, params=params, headers=headers, json={"url": image_url}) response.content results=response.json() results ``` 输出结果(开头加上face_data=) ``` face_data = [{'faceId': 'ddfd7889-2d5e-47f2-9b62-949fe1f71fe3', 'faceRectangle': {'top': 901, 'left': 506, 'width': 246, 'height': 246}, 'faceAttributes': {'smile': 0.402, 'headPose': {'pitch': -0.0, 'roll': 8.8, 'yaw': 2.0}, 'gender': 'male', 'age': 21.0, 'facialHair': {'moustache': 0.1, 'beard': 0.1, 'sideburns': 0.1}, 'glasses': 'NoGlasses', 'emotion': {'anger': 0.0, 'contempt': 0.015, 'disgust': 0.0, 'fear': 0.0, 'happiness': 0.402, 'neutral': 0.582, 'sadness': 0.0, 'surprise': 0.0}, 'blur': {'blurLevel': 'medium', 'value': 0.58}, 'exposure': {'exposureLevel': 'goodExposure', 'value': 0.64}, 'noise': {'noiseLevel': 'high', 'value': 0.75}, 'makeup': {'eyeMakeup': True, 'lipMakeup': True}, 'accessories': [], 'occlusion': {'foreheadOccluded': False, 'eyeOccluded': False, 'mouthOccluded': False}, 'hair': {'bald': 0.03, 'invisible': False, 'hairColor': [{'color': 'blond', 'confidence': 0.98}, {'color': 'brown', 'confidence': 0.78}, {'color': 'gray', 'confidence': 0.4}, {'color': 'black', 'confidence': 0.29}, {'color': 'other', 'confidence': 0.15}, {'color': 'red', 'confidence': 0.11}, {'color': 'white', 'confidence': 0.0}]}}}, {'faceId': 'cd07c6bf-d35a-4c4d-980c-ad69a8d9df06', 'faceRectangle': {'top': 190, 'left': 1406, 'width': 218, 'height': 218}, 'faceAttributes': {'smile': 0.999, 'headPose': {'pitch': 5.6, 'roll': -30.5, 'yaw': -11.1}, 'gender': 'male', 'age': 21.0, 'facialHair': {'moustache': 0.1, 'beard': 0.1, 'sideburns': 0.1}, 'glasses': 'NoGlasses', 'emotion': {'anger': 0.0, 'contempt': 0.0, 'disgust': 0.0, 'fear': 0.0, 'happiness': 0.999, 'neutral': 0.001, 'sadness': 0.0, 'surprise': 0.0}, 'blur': {'blurLevel': 'medium', 'value': 0.54}, 'exposure': {'exposureLevel': 'goodExposure', 'value': 0.71}, 'noise': {'noiseLevel': 'medium', 'value': 0.58}, 'makeup': {'eyeMakeup': True, 'lipMakeup': True}, 'accessories': [], 'occlusion': {'foreheadOccluded': False, 'eyeOccluded': False, 'mouthOccluded': False}, 'hair': {'bald': 0.09, 'invisible': False, 'hairColor': [{'color': 'blond', 'confidence': 0.98}, {'color': 'brown', 'confidence': 0.59}, {'color': 'black', 'confidence': 0.37}, {'color': 'other', 'confidence': 0.29}, {'color': 'red', 'confidence': 0.22}, {'color': 'gray', 'confidence': 0.2}, {'color': 'white', 'confidence': 0.0}]}}}, {'faceId': '2ef20955-d664-43c4-a718-30abe183090f', 'faceRectangle': {'top': 445, 'left': 361, 'width': 210, 'height': 210}, 'faceAttributes': {'smile': 0.001, 'headPose': {'pitch': -4.5, 'roll': -0.1, 'yaw': 2.4}, 'gender': 'male', 'age': 21.0, 'facialHair': {'moustache': 0.1, 'beard': 0.1, 'sideburns': 0.1}, 'glasses': 'NoGlasses', 'emotion': {'anger': 0.0, 'contempt': 0.0, 'disgust': 0.0, 'fear': 0.0, 'happiness': 0.001, 'neutral': 0.999, 'sadness': 0.0, 'surprise': 0.0}, 'blur': {'blurLevel': 'medium', 'value': 0.59}, 'exposure': {'exposureLevel': 'goodExposure', 'value': 0.54}, 'noise': {'noiseLevel': 'low', 'value': 0.17}, 'makeup': {'eyeMakeup': True, 'lipMakeup': True}, 'accessories': [], 'occlusion': {'foreheadOccluded': False, 'eyeOccluded': False, 'mouthOccluded': False}, 'hair': {'bald': 0.07, 'invisible': False, 'hairColor': [{'color': 'black', 'confidence': 1.0}, {'color': 'other', 'confidence': 0.71}, {'color': 'gray', 'confidence': 0.51}, {'color': 'brown', 'confidence': 0.42}, {'color': 'blond', 'confidence': 0.01}, {'color': 'red', 'confidence': 0.01}, {'color': 'white', 'confidence': 0.0}]}}}, {'faceId': '8cae7f53-e936-46b4-a129-b8c4c1a12b85', 'faceRectangle': {'top': 513, 'left': 799, 'width': 184, 'height': 184}, 'faceAttributes': {'smile': 0.0, 'headPose': {'pitch': 21.3, 'roll': -30.5, 'yaw': -10.6}, 'gender': 'male', 'age': 21.0, 'facialHair': {'moustache': 0.1, 'beard': 0.1, 'sideburns': 0.1}, 'glasses': 'NoGlasses', 'emotion': {'anger': 0.0, 'contempt': 0.0, 'disgust': 0.0, 'fear': 0.0, 'happiness': 0.0, 'neutral': 0.997, 'sadness': 0.003, 'surprise': 0.0}, 'blur': {'blurLevel': 'medium', 'value': 0.68}, 'exposure': {'exposureLevel': 'goodExposure', 'value': 0.67}, 'noise': {'noiseLevel': 'high', 'value': 1.0}, 'makeup': {'eyeMakeup': True, 'lipMakeup': True}, 'accessories': [], 'occlusion': {'foreheadOccluded': False, 'eyeOccluded': False, 'mouthOccluded': False}, 'hair': {'bald': 0.09, 'invisible': False, 'hairColor': [{'color': 'black', 'confidence': 0.97}, {'color': 'gray', 'confidence': 0.96}, {'color': 'other', 'confidence': 0.93}, {'color': 'blond', 'confidence': 0.13}, {'color': 'red', 'confidence': 0.03}, {'color': 'brown', 'confidence': 0.02}, {'color': 'white', 'confidence': 0.0}]}}}] ``` - 加入字典 ``` glasses = [] smile = [] hair_Color = [] age = [] gender = [] ``` - 眼镜佩戴 ``` glasses.append(face_data[0]['faceAttributes']['glasses']) glasses.append(face_data[1]['faceAttributes']['glasses']) glasses.append(face_data[2]['faceAttributes']['glasses']) glasses.append(face_data[3]['faceAttributes']['glasses']) print('glasses:',glasses) ``` 输出结果 ``` # glasses: ['NoGlasses', 'NoGlasses', 'NoGlasses', 'NoGlasses'] ``` - 笑容 ``` smile.append(face_data[0]['faceAttributes']['smile']) smile.append(face_data[1]['faceAttributes']['smile']) smile.append(face_data[2]['faceAttributes']['smile']) smile.append(face_data[3]['faceAttributes']['smile']) print('smile:',smile) ``` 输出结果 ``` smile: [0.402, 0.999, 0.001, 0.0] ``` - 头发颜色 ``` hair_Color.append(face_data[0]['faceAttributes']['hair']['hairColor'][0]['color']) hair_Color.append(face_data[1]['faceAttributes']['hair']['hairColor'][0]['color']) hair_Color.append(face_data[2]['faceAttributes']['hair']['hairColor'][0]['color']) hair_Color.append(face_data[3]['faceAttributes']['hair']['hairColor'][0]['color']) # 由于检测出的头发颜色多于一种,这里选取confidence最高的颜色 print('hair_Color:',hair_Color) ``` 输出结果 ``` hair_Color: ['blond', 'blond', 'black', 'black'] ``` - 年龄 ``` age.append(face_data[0]['faceAttributes']['age']) age.append(face_data[1]['faceAttributes']['age']) age.append(face_data[2]['faceAttributes']['age']) age.append(face_data[3]['faceAttributes']['age']) print('age:',age) ``` 输出结果 ``` age: [21.0, 21.0, 21.0, 21.0] ``` - 性别 ``` gender.append(face_data[0]['faceAttributes']['gender']) gender.append(face_data[1]['faceAttributes']['gender']) gender.append(face_data[2]['faceAttributes']['gender']) gender.append(face_data[3]['faceAttributes']['gender']) print('gender:',gender) ``` 输出结果 ``` gender: ['male', 'male', 'male', 'male'] ```