热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

《python编程从入门到实践》笔记(2)

《python编程从入门到实践》笔记(2)----20191122chap6字典python中,字典是一系列的键值对,每个键都与一个值

《python编程从入门到实践》笔记(2) ----20191122

chap6 字典

python中,字典是一系列的键值对,每个键都与一个值相关联,可以使用键来访问与之相关联的值。
与键相关联的值可以是数字,字符串,列表,字典,任何python对象都可用作字典中的值。

#1.创建一个字典
alien_0 = {'color':'green','points':5}
print(alien_0)#2.添加键值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)#3.修改字典中的值
print("The alien is "+alien_0['color']+".")alien_0['color'] = 'yellow'
print("The alien is now "+alien_0['color']+".")#4.小案例
"""
对一个能够以不同速度移动的外星人的位置进行跟踪,
为此,我们将存储该外星人的当前速度,并据此确定该外星人将向右移动多远
"""
alien_0 = {'x_position':0,'y_position':25,'speed':'medium'}
print("\nOriginal x-positon :"+str(alien_0['x_position']))#向右移动外星人
#根据外星人当前速度决定其移动多远
if alien_0['speed'] == 'slow':x_increment = 1
elif alien_0['speed'] == 'medium':x_increment = 2
else:#这个外星人的速度一定很快x_increment = 3#新位置等于老位置加上增量
alien_0['x_position'] = alien_0['x_position']+x_increment
print("New x-position:"+str(alien_0['x_position']))#5.删除键值对:del
del alien_0['speed']
print(alien_0)#6.由类似对象组成的字典,假设要调查很多人,询问他们喜欢的编程语言
"""使用字典存储众多对象的同一种信息"""
favorite_languages = {'jen':'python','sarah':'c','edward':'ruby','phil':'python',#在最后一个键值对后面也加上逗号,为以后在下一行添加键值对做准备
}print("\nSarah's favorite languages is "+favorite_languages['sarah'].title()+".")#7.遍历字典中的键值对,items返回一个键值对列表
for name ,languanges in favorite_languages.items():print(name.title()+"'s favorite languagr is"+languanges.title()+".")print("")
#8.遍历字典中的键
for name in favorite_languages.keys():print(name.title())#9.按顺序遍历字典中的所有键,并不改变原有的字典中的顺序
for name in sorted(favorite_languages.keys()):print(name.title()+", thank you for taking the poll")#10.遍历字典中的所有值
print("\nThe favorite languages hav been etioned:")
for language in favorite_languages.values():print(language.title())#11.使用set取出重复值
print("\nThe following languages hav been etioned:")
for language in set(favorite_languages.values()):print(language.title())#12.嵌套:将字典存在列表中,或者将列表作为值存在字典中
#字典列表:创建一个外星人列表,每个列表都是一个字典alien_0 = {'color':'green','point':5}
alien_1 = {'color':'yellow','points':10}
alien_2 = {'color':'red','points':15}
aliens = [alien_0,alien_1,alien_2]
for alien in aliens:print(alien)#更符合现实的是:外星人不止3个,且每个外星人都是用代码自动生成的#创建一个用于存储外星人的空列表
aliens =[]
#创建30个绿色的外星人
for alien_number in range(30):new_alien = {'color':'green','points':5,'speed':'slow'}aliens.append(new_alien)#显示前5个外星人
for alien in aliens[:5]:print(alien)
print("...")
print("Total number of aliens:"+str(len(aliens)))#我们可以独立的修改每个外星人
for alien in aliens[:3]:if alien['color'] == 'green':alien['color'] = 'yellow'alien['points'] = 10alien['speed'] = 'medium'#显示前五个外星人
for alien in aliens[:5]:print(alien)
print("...")#在字典中存储列表
#使用字典,存储要添加的披萨配料以及其它描述(如:外皮类型)
#存储所点披萨的信息
pizza = {'crust':'thick','toppings':['mudhrooms','extra cheese'],
}#概述所点披萨
print("You ordered a " +pizza['crust']+"-crust pizza "+"with the following toppings:")
for topping in pizza['toppings']:print("\t"+topping)#当字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表,
#例2:调查喜欢的编程语言:一个人可以喜欢多种
favorite_languages = {'jen':['python','ruby'],'sarah':['c'],'edward':['ruby','go'],'phil':['pyhon','haskell'],
}for name,languages in favorite_languages.items():print("\n"+name.title()+"'s favorite languages are:")for language in languages:print("\t"+language.title())#13.在字典中存储字典
"""
有多个网站用户,每个用户都有独特的用户名,可在字典中将用户名作为键
然后将每位用户的信息存储在一个字典中,并将该字典作为与用户名先关联的值
"""

#对每个用户存储:名,姓和居住地
users = {'aeinstein':{'first':'albert','last':'einstein','location':'princeton',},'mcurie':{'first':"marie",'last':'curie','location':'paris',},
}for username,user_info in users.items():print("\nUsernae:"+username)full_name = user_info['first']+" "+user_info['last']location = user_info['location']print("\tFull name:"+full_name.title())print("\tLocation:"+location.title())

输出结果:

{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
The alien is green.
The alien is now yellow.Original x-positon :0
New x-position:2
{'x_position': 2, 'y_position': 25}Sarah's favorite languages is C.
Jen'
s favorite languagr isPython.
Sarah's favorite languagr isC.
Edward'
s favorite languagr isRuby.
Phil's favorite languagr isPython.Jen
Sarah
Edward
Phil
Edward, thank you for taking the poll
Jen, thank you for taking the poll
Phil, thank you for taking the poll
Sarah, thank you for taking the pollThe favorite languages hav been etioned:
Python
C
Ruby
PythonThe following languages hav been etioned:
Ruby
C
Python
{'
color': 'green', 'point': 5}
{'
color': 'yellow', 'points': 10}
{'
color': 'red', 'points': 15}
{'
color': 'green', 'points': 5, 'speed': 'slow'}
{'
color': 'green', 'points': 5, 'speed': 'slow'}
{'
color': 'green', 'points': 5, 'speed': 'slow'}
{'
color': 'green', 'points': 5, 'speed': 'slow'}
{'
color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens:30
{'
color': 'yellow', 'points': 10, 'speed': 'medium'}
{'
color': 'yellow', 'points': 10, 'speed': 'medium'}
{'
color': 'yellow', 'points': 10, 'speed': 'medium'}
{'
color': 'green', 'points': 5, 'speed': 'slow'}
{'
color': 'green', 'points': 5, 'speed': 'slow'}
...
You ordered a thick-crust pizza with the following toppings:mudhroomsextra cheeseJen'
s favorite languages are:PythonRubySarah's favorite languages are:CEdward's favorite languages are:RubyGoPhil's favorite languages are:PyhonHaskellUsernae:aeinsteinFull name:Albert EinsteinLocation:PrincetonUsernae:mcurieFull name:Marie CurieLocation:Paris

chap 7 用户输入和while循环

通过获取用户输入并学会控制程序的运行实践,可编写出交互式程序

1.提示超过一行,可将提示存储在一个变量中,再将该变量传递给函数input()

2.使用break退出循环:立刻退出while循环,不在运行循环中余下的代码
3.continue:返回到循环开头,并根据条件测试结果决定是否继续执行循环
4避免无限循环
5.使用while循环来处理列表和字典

#1提示超过一行,可将提示存储在一个变量中,再将该变量传递给函数input()
prompt = "If you tell us ho you are ,we can personalize the message you see."
prompt += "\nWhat is your first name?"
name = input(prompt)
print("\nHello, "+ name +"!")#2.使用while循环处理列表和字典
"""
for循环是一种遍历列表的有效方式,但是在for循环中不应修改列表,这将导致python难以跟踪其中的元素
要在遍历列表的同时对齐进行修改,可使用while循环
"""
#假设一个列表,其中包含寻注册但还未验证的网站用户;
# 使用while循环,在验证这些用户的同时将其从未验证用户列表中提取出来,加入到另一个已验证用户列表中#首先创建一个待验证用户列表和一个存储已验证用户的空列表
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []#验证每个用户,直到没有未验证用户为止
#将每个经过验证的用户都移动到已验证用户列表中
while unconfirmed_users:current_suer = unconfirmed_users.pop()print("Verifying user:"+current_suer.title())confirmed_users.append(current_suer)#显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:print(confirmed_user.title())#删除包含特定值的所有列表元素
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)while 'cat' in pets:pets.remove('cat')print(pets)#使用用户输入来天聪字典
responses = {}
#设置一个标志,指出调查是否继续
polling_active = True
while polling_active:#提示用户输入被调查者的名字和回答name = input("\nWhat is your name?")response =input("which mountain would you like to climb someday?")#将答卷存储在字典中responses[name] = response#看看是否还有人要参与调查repeat = input("woulid you like to let another person respond?(yes/no)")if repeat == 'no' or repeat == "NO":polling_active = False#调查结果,显示结果
print("\n----poll results ----")
for name ,response in responses.items():print(name +" would like to climb "+response+".")

运行结果:

If you tell us ho you are ,we can personalize the message you see.
What is your first name?EircHello, Eirc!
Verifying user:Candace
Verifying user:Brian
Verifying user:AliceThe following users have been confirmed:
Candace
Brian
Alice
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']What is your name?Eric
which mountain would you like to climb someday?Lynn
woulid you like to let another person respond?(yes/no)no----poll results ----
Eric would like to climb Lynn.

推荐阅读
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • Docker的安全基准
    nsitionalENhttp:www.w3.orgTRxhtml1DTDxhtml1-transitional.dtd ... [详细]
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • 技术分享:从动态网站提取站点密钥的解决方案
    本文探讨了如何从动态网站中提取站点密钥,特别是针对验证码(reCAPTCHA)的处理方法。通过结合Selenium和requests库,提供了详细的代码示例和优化建议。 ... [详细]
  • 非公版RTX 3080显卡的革新与亮点
    本文深入探讨了图形显卡的进化历程,重点介绍了非公版RTX 3080显卡的技术特点和创新设计。 ... [详细]
  • 本文详细介绍了 GWT 中 PopupPanel 类的 onKeyDownPreview 方法,提供了多个代码示例及应用场景,帮助开发者更好地理解和使用该方法。 ... [详细]
  • Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • python的交互模式怎么输出名文汉字[python常见问题]
    在命令行模式下敲命令python,就看到类似如下的一堆文本输出,然后就进入到Python交互模式,它的提示符是>>>,此时我们可以使用print() ... [详细]
  • 本文详细介绍了如何在Linux系统上安装和配置Smokeping,以实现对网络链路质量的实时监控。通过详细的步骤和必要的依赖包安装,确保用户能够顺利完成部署并优化其网络性能监控。 ... [详细]
  • Python 异步编程:深入理解 asyncio 库(上)
    本文介绍了 Python 3.4 版本引入的标准库 asyncio,该库为异步 IO 提供了强大的支持。我们将探讨为什么需要 asyncio,以及它如何简化并发编程的复杂性,并详细介绍其核心概念和使用方法。 ... [详细]
  • 本文详细介绍 Go+ 编程语言中的上下文处理机制,涵盖其基本概念、关键方法及应用场景。Go+ 是一门结合了 Go 的高效工程开发特性和 Python 数据科学功能的编程语言。 ... [详细]
  • 本文详细介绍了Java中org.neo4j.helpers.collection.Iterators.single()方法的功能、使用场景及代码示例,帮助开发者更好地理解和应用该方法。 ... [详细]
  • 本文探讨了Hive中内部表和外部表的区别及其在HDFS上的路径映射,详细解释了两者的创建、加载及删除操作,并提供了查看表详细信息的方法。通过对比这两种表类型,帮助读者理解如何更好地管理和保护数据。 ... [详细]
  • 本文详细介绍了如何在BackTrack 5中配置和启动SSH服务,确保其正常运行,并通过Windows系统成功连接。涵盖了必要的密钥生成步骤及常见问题解决方法。 ... [详细]
author-avatar
up61
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有