# python_week06 **Repository Path**: Elaine111/python_week06 ## Basic Information - **Project Name**: python_week06 - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-11-02 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Python week06 ------ ## 作业要求 > 1. 总结关于字典、集合的所有方法 请自行练习关于字典(dict)以及集合(set)相关内容,并做总结。 >2. 猜数字练习 课上已演示过,请自行再次练习 > 3. 课本代码练习 关于第三章p95~p144的代码 > 4. 字典查询练习 Azure API 提供一张含有>=3张脸(3个以上faceid)的图片,先用json()获取内容(results),在用数据结构查询的方式查找到:眼镜、肤色、微笑指数、头发颜色、年龄、性别这几项数据,并分别存进变量/自定义数据结构(如字典等)当中。 ------ ## 我的答案 ### 字典、集合的方法 #### 字典 **字典:字典是另一种可变容器模型,且可存储任意类型对象** **字典内置函数&方法** |序号|函数|描述| |:---|---:|:--:| |1|len(dict)|计算字典元素个数,即键的总数。| |2|str(dict)|输出字典,以可打印的字符串表示。| |3|type(variable)|返回输入的变量类型,如果变量是字典就返回字典类型。| *** |序号|方法|描述| |:---|---:|:--:| |1|dict.clear()|删除字典内所有元素| |2|dict.copy()|返回一个字典的浅复制| |3|dict.fromkeys()|创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值| |4|dict.get(key, default=None)|返回指定键的值,如果键不在字典中返回 default 设置的默认值| |5|key in dict|如果键在字典dict里返回true,否则返回false| |6|dict.items()|以列表返回可遍历的(键, 值) 元组数组| |7|dict.keys()|返回一个迭代器,可以使用 list() 来转换为列表| |8|dict.setdefault(key, default=None)|和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default| |9|dict.update(dict2)|把字典dict2的键/值对更新到dict里| |10|dict.values()|返回一个迭代器,可以使用 list() 来转换为列表| |11|dict.pop(key[,default])|删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。| |12|dict.popitem()|随机返回并删除字典中的最后一对键和值。| #### 集合 **集合(set)是一个无序的不重复元素序列** **集合的方法** |序号|方法|描述| |:---|---:|:--:| |1|set.add()|为集合添加元素| |2|set.clear()|移除集合中的所有元素| |3|set.copy()|拷贝一个集合| |4|set.difference()|返回多个集合的差集| |5|set.difference_update()|移除集合中的元素,该元素在指定的集合也存在。| |6|set.discard()|删除集合中指定的元素| |7|set.intersecrion()|返回集合的交集| |8|set.intersection_update()|返回集合的交集| |9|ste.isdisjoint()|判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。| |10|set.issubset()|判断指定集合是否为该方法参数集合的子集。| |11|set.issuperset()|判断该方法的参数集合是否为指定集合的子集| |12|set.pop()|随机移除元素| |13|set.remove()|移除制定元素| |14|set.symmetric_difference()|返回两个集合中不重复的元素集合。| |15|set.symmetric_difference_update()|移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。| |16|set.union()|返回两个集合的并集| |17|set.update()|给集合添加元素| ### 猜数字练习 代码如下: ```python import random hide_card = random.randint(1,100) #限制随机数字大小 count = 0 if hide_card <100 and hide_card >0: while True: if count <3: # 设置猜测次数 guess = input("请输入你猜想的数字") guess_digit = int(guess) if guess_digit == hide_card: print("猜对啦!") break elif guess_digit>hide_card: print("太大了") else: print("太小了") count +=1 else: print("还是不对哦!") print("正确答案:%s"%(hide_card)) break 运行结果: ```python 请输入你猜想的数字66 太大了 请输入你猜想的数字55 太大了 请输入你猜想的数字44 太大了 还是不对哦! 正确答案:22 ``` ------ ### 课本代码练习p95-144 #### 字典查询练习p101 ```python person3={'name':'ford perfect','gender':'male','home planet':'betelgeuse seven','occupation':researcher,'age':33} print(person3['age'] # 33 ``` #### 元音字母练习P102 ```python vowels = ['a', 'e', 'i', 'o', 'u'] word = input('请输入单词') found = [] for letter in word: if letter in vowels: if letter not in found: found.append(letter) for vowel in found: print(vowels) ``` 运行结果 #### 元音字母练习P113 ```python vowels=['a','e','i','o','u'] word=input('请输入单词') found={} found['a']=0 found['e']=0 found['i']=0 #将key和value放进字典中 found['o']=0 found['u']=0 for letter in word: if letter in vowels: found[letter]+=1 #对应的key的value值加1 for k,v in sorted(found.items()): #found.items()可以输出字典中的key和value k=key v=value sorted可以保持输出的殊勋 print (k,'was found',v, 'time(s).') ``` 运行结果 ``` #### setdefault练习P120 ```python vowels=['a','e','i','o','u'] word=input('请输入想要检测的字符串') found={} for letter in word: if letter in vowels: found.setdefault(letter,0) found[letter]+=1 for k,v in sorted(found.items()): print(k,'was found',v,'times') ``` #### 集合创建P124-130 ```python >>> vowels={'a','b','a'} >>> vowels {'a', 'b'} >>> vowels=set('aba') >>> vowels {'a', 'b'} >>> vowels=set('aeiou') >>> word='hello' >>> u=vowels.union(set(word)) >>> u {'a', 'o', 'u', 'l', 'h', 'e', 'i'} >>> d=vowels.difference(set(word)) >>> d {'a', 'u', 'i'} >>> u_list=sorted(list(u)) >>> u_list ['a', 'e', 'h', 'i', 'l', 'o', 'u'] >>> i=vowels.intersection(word) >>> i {'o', 'e'} >>> ``` ### 元音练习3.0 ```python vowels=set('aeiou') #把元音字母建立一个集合 word=input('请输入想要检测的单词') found=vowels.intersection(set(word)) #将input与vowels的交集得出 for vowels in found: print(vowels) ``` 练习结果 ------ ### 字典查询练习 Azure API 提供一张含有>=3张脸(3个以上faceid)的图片,先用json()获取内容(results),在用数据结构查询的方式查找到:眼镜、肤色、微笑指数、头发颜色、年龄、性别这几项数据,并分别存进变量/自定义数据结构(如字典等)当中。 ①首先根据在API课上学到的知识,用Azure API分析一张含有3张及以上的人脸照片 代码如下: ```python import requests # 准备工作,记得输入 face_api_url = 'https://face-ozl.cognitiveservices.azure.com/face/v1.0/detect' # 请求正文 image_url = 'https://upload-images.jianshu.io/upload_images/25012790-d039fcac5b4fe7ce.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 ``` 输出结果如下: ```python # 我选用了一张有3张人脸的图片,所以这里总共有3张脸的数据 # 这里将这个字典嵌套列表命名为face_data face_data = [{'faceId': '14a6e987-0203-4e2c-a641-594e828ccce4', # 第1张脸 'faceRectangle': {'top': 93, 'left': 720, 'width': 111, 'height': 111}, 'faceAttributes': {'smile': 0.0, # 我们需要提取的数据之一'微笑指数' 'headPose': {'pitch': -7.9, 'roll': -0.8, 'yaw': -2.6}, 'gender': 'male', # 我们需要提取的数据之一'性别' 'age': 22.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': 1.0, 'sadness': 0.0, 'surprise': 0.0}, 'blur': {'blurLevel': 'medium', 'value': 0.5}, 'exposure': {'exposureLevel': 'goodExposure', 'value': 0.64}, 'noise': {'noiseLevel': 'medium', 'value': 0.56}, 'makeup': {'eyeMakeup': True, 'lipMakeup': True}, 'accessories': [], 'occlusion': {'foreheadOccluded': False, 'eyeOccluded': False, 'mouthOccluded': False}, 'hair': {'bald': 0.05, 'invisible': False, 'hairColor': [{'color': 'black', 'confidence': 1.0}, # 我们需要提取的数据之一'头发颜色' {'color': 'brown', 'confidence': 0.68}, {'color': 'other', 'confidence': 0.44}, {'color': 'gray', 'confidence': 0.32}, {'color': 'blond', 'confidence': 0.07}, {'color': 'red', 'confidence': 0.01}, {'color': 'white', 'confidence': 0.0}]}}}, {'faceId': '2ff8fca6-d92b-4647-b221-f5605014f827', # 第2张脸 'faceRectangle': {'top': 92, 'left': 432, 'width': 107, 'height': 107}, 'faceAttributes': {'smile': 0.0, 'headPose': {'pitch': -9.7, 'roll': 0.6, 'yaw': -3.3}, 'gender': 'male', 'age': 22.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.999, 'sadness': 0.0, 'surprise': 0.0}, 'blur': {'blurLevel': 'medium', 'value': 0.26}, 'exposure': {'exposureLevel': 'goodExposure', 'value': 0.6}, 'noise': {'noiseLevel': 'low', 'value': 0.18}, 'makeup': {'eyeMakeup': True, 'lipMakeup': True}, 'accessories': [], 'occlusion': {'foreheadOccluded': False, 'eyeOccluded': False, 'mouthOccluded': False}, 'hair': {'bald': 0.02, 'invisible': False, 'hairColor': [{'color': 'black', 'confidence': 1.0}, {'color': 'brown', 'confidence': 0.91}, {'color': 'other', 'confidence': 0.34}, {'color': 'gray', 'confidence': 0.24}, {'color': 'blond', 'confidence': 0.03}, {'color': 'red', 'confidence': 0.02}, {'color': 'white', 'confidence': 0.0}]}}}, {'faceId': 'affa9f14-0676-4d9b-aedc-e9d6ac531382', # 第3张脸 'faceRectangle': {'top': 87, 'left': 117, 'width': 107, 'height': 107}, 'faceAttributes': {'smile': 0.003, 'headPose': {'pitch': -7.5, 'roll': 1.2, 'yaw': -4.6}, 'gender': 'male', 'age': 22.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.003, 'neutral': 0.996, 'sadness': 0.0, 'surprise': 0.0}, 'blur': {'blurLevel': 'medium', 'value': 0.27}, 'exposure': {'exposureLevel': 'goodExposure', 'value': 0.48}, 'noise': {'noiseLevel': 'low', 'value': 0.08}, 'makeup': {'eyeMakeup': True, 'lipMakeup': True}, 'accessories': [], 'occlusion': {'foreheadOccluded': False, 'eyeOccluded': False, 'mouthOccluded': False}, 'hair': {'bald': 0.02, 'invisible': False, 'hairColor': [{'color': 'brown', 'confidence': 0.99}, {'color': 'black', 'confidence': 0.97}, {'color': 'red', 'confidence': 0.19}, {'color': 'other', 'confidence': 0.11}, {'color': 'gray', 'confidence': 0.1}, {'color': 'blond', 'confidence': 0.04}, {'color': 'white', 'confidence': 0.0}]}}}] ``` ②然后我们来分别创建'眼镜、肤色、微笑指数、头发颜色、年龄、性别'这几个数据的空列表 ```python glasses = [] smile = [] hair_Color = [] age = [] gender = [] ``` ③最后,我们通过查询字典对应key及列表.append方法把数据分别加入以上对应列表,然后打印出来看看是否加入成功 * glasses 代码如下: ```python glasses.append(face_data[0]['faceAttributes']['glasses']) glasses.append(face_data[1]['faceAttributes']['glasses']) glasses.append(face_data[2]['faceAttributes']['glasses']) print('glasses:',glasses) ``` 输出结果如下: ```python glasses:['NoGlasses','NoGlasses','NoGlasses'] ``` * smile 代码如下: ```python smile.append(face_data[0]['faceAttributes']['smile']) smile.append(face_data[1]['faceAttributes']['smile']) smile.append(face_data[2]['faceAttributes']['smile']) print('smile:',smile) ``` 输出结果如下: ```python smile:[0.0,0.0,0.003] ``` * hair_Color 代码如下: ```python 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']) # 由于检测出的头发颜色多于一种,这里选取confidence最高的颜色 print('hair_Color:',hair_Color) ``` 输出结果如下: ```python hair_Color:['black','black','brown'] ``` * age 代码如下: ```python age.append(face_data[0]['faceAttributes']['age']) age.append(face_data[1]['faceAttributes']['age']) age.append(face_data[2]['faceAttributes']['age']) print('age:',age) ``` 输出结果如下: ```python age:[22.0,22.0,22.0] ``` * gender 代码如下: ```python gender.append(face_data[0]['faceAttributes']['gender']) gender.append(face_data[1]['faceAttributes']['gender']) gender.append(face_data[2]['faceAttributes']['gender']) print('gender:',gender) ``` 输出结果如下: ```python gender:['male','male','male']