技术标签: python 蓝桥杯Python B组练习 开发语言
复习python,参考书《Python编程从入门到实践》,[美]Eric Mathes著。前一部分见专栏——蓝桥杯Python B组练习
这一部分不全,不想写了
来看一个游戏,其中包含一些外星人,这些外星人的颜色和点数各不相同。下面是一个简单的字典,存储了有关特定外星人的信息:
alien_0={'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])
运行结果:
green
5
在Python中,字典是一系列键-值对。每个键都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。
在Python中,字典用放在花括号{}中的一系列键-值对表示,如下:
alien_0={'color':'green','points':5}
键值对是两个相关联的值。指定键是Python将返回与之相关联的值。键和值之间用冒号分隔,而键值对之间用逗号分隔。
1)访问键值对
print(alien_0['color'])
2)添加键值对
alien_0={'color':'green','points':5}
alien_0['x_position']=0
alien_0['y_position']=0
print(alien_0)
运行结果:
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 0}
3)先创建一个空字典
有时候,在空字典中添加键值对是为了方便,而有时候必须这样做。
alien_0={}
alien_0['color']='green'
alien_0['points']=5
print(alien_0)
运行结果:
{'color': 'green', 'points': 5}
4)修改字典中的值
alien_0={}
alien_0['color']='green'
alien_0['points']=5
print(alien_0)
alien_0['color']='yellow'
print(alien_0)
运行结果:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 5}
5)删除键值对
对于字典中不再需要的信息,可使用del语句将相应的键值对彻底删除。使用del语句时,必须指定字典名和要删除的键。
alien_0={'color':'green','points':5}
print(alien_0)
del alien_0['points']
print(alien_0)
运行结果:
{'color': 'green', 'points': 5}
{'color': 'green'}
1)遍历所有的键值对
user_0 = {
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for key,value in user_0.items():
print("\nKey:"+key)
print("Value:"+value)
如上所示,编写for循环,可声明两个变量,用于存储键值对中的键和值。对于这两个变量,可使用任何名称。
如:for k,v in user_0.items()
运行结果:
Key:username
Value:efermi
Key:first
Value:enrico
Key:last
Value:fermi
2)遍历字典中的所有键
user_0 = {
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for k in user_0.keys():
print(k.title())
运行结果:
Username
First
Last
还可以使用keys()确定某个键是否在keys中。
user_0 = {
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
if 'second_name' not in user_0.keys():
方法keys()并非只能用于遍历;实际上,它返回一个列表,其中包含字典中的所有键。
运行结果:
Please take out poll
3)按顺序遍历字典中的所有键
要以特定的顺序返回元素,一种办法是在for循环中返回的键进行排序。为此,可使用函数sorted()来获得按特定顺序排序的键列表的副本:
user_0 = {
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for k in sorted(user_0.keys()):
print(k.title())
运行结果:
First
Last
Username
4)遍历字典中的所有值
如果你感兴趣的主要是字典包含的值,可使用方法values(),它返回一个值列表,而不包含任何键。
user_0 = {
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for v in user_0.values():
print(v.title())
运行结果:
Efermi
Enrico
Fermi
这样的做法提取字典的所有值,而没有考虑是否重复。为剔除重复项,可使用集合(set)。集合类似于列表,但每一个元素都必须是独一无二的:
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for language in set(favorite_languages.values()):
print(language.title())
运行结果:
C
Python
Ruby
有时候,需要将一系列字典存储在列表中,或者将列表作为值存储在字典中,这称为嵌套。
1)字典列表
alien_0 ={'color':'green','points':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)
运行结果:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
2)在字典中存储列表
有时候需要将列表存储在字典中,而不是将字典存储在列表中。
#存储所点披萨的信息
pizza ={
'crust':'thick',
'toppings':['mushrooms','extra cheese'],
}
#概述所点的披萨
print("You ordered a"+pizza['crust']+"-crust pizza"+"with the following toppings:")
for topping in pizza['toppings']:
print("\t"+topping)
运行结果:
You ordered athick-crust pizzawith the following toppings:
mushrooms
extra cheese
3)在字典中存储字典
users = {
'aeinstein':{'first':'albert',
'last':'einstein',
'location':'princeton',
},
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris',
},
}
for username,user_info in users.items():
print("\nUsername:"+username)
full_name=user_info['first']+" "+user_info['last']
location = user_info['location']
print("\tFull name:"+full_name.title())
print("\tLocation:"+location.title())
运行结果:
Username:aeinstein
Full name:Albert Einstein
Location:Princeton
Username:mcurie
Full name:Marie Curie
Location:Paris
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。
name=input("Please enter your name:")
print("Hello,"+name+"!")
运行结果:
Please enter your name:Eric
Hello,Eric!
1)使用int()来获取数值输入
age=input("How old are you?")
age>=18
如上,用户输入的是数字21,但我们请求Python提供变量age时,它返回的是‘21’——用户输入的数值的字符串表示。如果试图将输入作为数字使用,就会引发错误:
为解决这个问题,可以用函数int()
age=input("How old are you?")
age=int(age)
if age>=18:
print("True")
运行结果:
2)求模运算符
处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数:
print(4%3)
print(5%3)
print(6%3)
print(7%3)
运行结果:
1
2
0
1
1)使用while循环
使用while循环来数数,例如,下面的while循环从1数到5:
current_number=1
while current_number <=5:
print(current_number)
current_number+=1
运行结果:
1
2
3
4
5
2)让用户选择何时退出
prompt = "\nTell me something,and I will repeat it back to you:"
prompt=prompt+"\nEnter 'quit' to end the program."
message=""
while message !='quit':
message=input(prompt)
print(message)
运行结果:
Python首次执行while语句时,需要将message的值与‘quit’进行比较,但此时用户还没有输入。如果没有可供比较的东西,Python将无法继续运行程序。为解决这个问题,我们必须给变量message指定一个初始值。虽然这个初始值只是一个空字符串,但符合要求,让Python能够执行while循环所需的比较。只需要message的值不是‘quit’,这个循环就会不断运行。
3)使用标志
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志。充当了程序的交通信号灯。你可让程序在标志为True时继续运行,并在任何事件导致标志值为False时让程序停止运行。
prompt = "\nTell me something,and I will repeat it back to you:"
prompt=prompt+"\nEnter 'quit' to end the program."
active = True
while active:
message=input(prompt)
if message == 'quit':
active = False
else:
print(message)
运行结果:
4)使用break退出循环
要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句。
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.)"
while True:
city=input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to"+city.title()+"!")
运行结果:
注意:在任何循环中都可使用break语句。例如,可使用break语句来退出遍历列表或字典的for循环。
5)在循环中使用continue
要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下的代码并退出整个循环。
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.)"
while True:
city=input(prompt)
if city == 'quit':
continue
else:
print("I'd love to go to"+city.title()+"!")
运行结果:
如运行结果显示,陷入无限循环,无法跳出循环,我们应该避免无限循环。如果程序陷入无限循环,可按Ctrl+C,也可关闭显示程序的终端窗口。
1)在列表之间移动元素
unconfirmed_users=['alice','brian','candace']
confirmed_users=[]
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user:"+ current_user.title())
confirmed_users.append(current_user)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
运行结果:
2)删除包含特定值的所有列表元素
我们使用函数remove()来删除列表中的特定值,这之所以可行,是因为要删除的值在列表中值出现了一次。
假设你有一个宠物列表,其中包含多个值为’cat‘的元素。要删除所有这些元素,可不断运行一个while循环,直到列表中不再包含值’cat‘,如下所示:
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
运行结果:
3)使用用户输入来填充字典
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("Would you like to let another person respond?(yes/no)")
if repeat == 'no':
polling_active = False
print("\n--------Poll Result------")
for name,response in responses.items():
print(name+"would like to climb"+response+".")
运行结果:
下面是一个打印问候语的简单函数,名为greet_user():
def greet_user():
print("Hello!")
greet_user()
第一行的代码使用关键字def来告诉Python你要定义一个函数。这是函数定义,向Python指出了函数名。第二行函数体,第三行执行函数,打印Hello!
1)向函数传递信息
def greet_user(username):
print("Hello!"+username.title()+"!")
greet_user('jesse')
运行结果:
Hello!Jesse!
向函数传递实参的方式很多,可使用位置实参,这要求实参的顺序与形参顺序相同;也可使用关键字实参,其中每个实参都由变量名和值组成。
1)位置实参
def descirbe_pet(animal_type,pet_name):
print("\nI have a "+animal_type+".")
print("My" + animal_type+"'s name is"+pet_name.title()+".")
descirbe_pet('hamster','harry')
运行结果:
注意:位置实参的顺序很重要
2)关键字实参
关键字实参是传递函数的名称-值对。
def descirbe_pet(animal_type,pet_name):
print("\nI have a "+animal_type+".")
print("My" + animal_type+"'s name is"+pet_name.title()+".")
descirbe_pet(animal_type='hamster',pet_name='harry')
运行结果:
3)默认值
编写函数时,可给每个形参指定默认值。
def descirbe_pet(pet_name,animal_type='dog'):
print("\nI have a "+animal_type+".")
print("My" + animal_type+"'s name is"+pet_name.title()+".")
descirbe_pet(pet_name='harry')
运行结果:
注意:使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的形参。
这让Python依然能够正确地解读位置实参。
函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值。
1)返回简单值
def get_formatted_name(first_name,last_name):
full_name=first_name+' '+last_name
return full_name.title()
musician = get_formatted_name('jimi','hendrix')
print(musician)
运行结果:
Jimi Hendrix
2)让实参变成可选的
并非所有人都有中间名,为让中间名变成可选的,可采用如下:
def get_formatted_name(first_name,last_name,middle_name=''):
full_name=first_name+' '+middle_name+' '+last_name
return full_name.title()
musician = get_formatted_name('jimi','hendrix')
print(musician)
musician = get_formatted_name('john','hooker','lee')
print(musician)
给实参middle_name指定一个默认值——空字符串,并在用户没有提供中间名时不使用这个实参。为让get_formatted_name()在没有提供中间名时依然可以运行,可给实参middle_name指定一个默认——空字符串,并将其移到形参列表末尾。
运行结果:
3)返回字典
def build_person(first_name,last_name):
person = {'first':first_name,'last':last_name}
return person
musician = build_person('jimi','hendrix')
print(musician)
运行结果:
{'first': 'jimi', 'last': 'hendrix'}
4)结合使用函数和while循环
def get_formatted_name(first_name,last_name):
full_name = first_name+' '+last_name
return full_name.title()
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any time to quit)")
f_name = input("First name: ")
if f_name == 'q':
break
l_name = input("Last name:")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name,l_name)
print("\nHello,"+ formatted_name+"!")
运行结果:
假设有一个用户列表,我们要问候其中的每位用户。下面示例将一个名字列表传递给一个名为greet_users()的函数,这个函数问候列表中的每个人:
def greet_uers(names):
for name in names:
msg = "Hello, "+name.title()+"!"
print(msg)
usernames=['hannah','ty','margot']
greet_uers(usernames)
运行结果:
函数只有一个形参*toppings,不管调用语句提供了多少实参,这个形参都将它们统统收入囊中:
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
运行结果:
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
1)结合使用位置实参和任意数量实参
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。
def make_pizza(size,*toppings):
print("\nMaking a "+str(size)+"-inch pizza with the following toppings:")
for topping in toppings:
print("- "+topping)
make_pizza(16,'pepperoni')
make_pizza(20,'mushrooms','green peppers','extra cheese')
运行结果:
2)使用任意数量的关键字实参
有时候,需要接受任意数量的实参,但预先不知道传递给函数的是什么样的信息。
在下面的实例中,函数build_profile()接受名和姓,同时还接受任意数量的关键字实参:
def build_profile(first,last,**user_info):
profile={}
profile['first_name']=first
profile['last_name']=last
for key,value in user_info.items():
profile[key]=value
return profile
user_profile = build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)
运行结果:
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
略
使用类几乎可以模拟任何东西。
1)创建Dog类
class Dog():
def __init__(self,name,age):
self.name=name
self.age=age
def sit(self):
print(self.name.title()+"is now sitting.")
def roll_over(self):
print(self.name.title()+"rolled over!")
类中的函数称为方法;前面学的有关函数的一切都适用于方法,就目前而言,唯一重要的差别是调用方法的方式。__init__()是一个特殊的方法,每当你根据Dog类创建新实列时,Python都会自动运行它。在这个方法的名称中,开头和末尾各有两个下划线,这是一种约定,旨在避免Python默认方法与普通方法发生的名称冲突。__init__()中包含了三个形参:self、name和age。在这个方法的定义中,形参self必不可少,还必须位于其他形参前面。
2)根据类创建实例
1.访问属性
my_dog.name
class Dog():
def __init__(self,name,age):
self.name=name
self.age=age
def sit(self):
print(self.name.title()+"is now sitting.")
def roll_over(self):
print(self.name.title()+"rolled over!")
my_dog = Dog('willie',6)
print("My dog's name is"+my_dog.name.title()+'.')
print("My dog is"+str(my_dog.age)+"years old.")
运行结果:
My dog's name isWillie.
My dog is6years old.
2.调用方法
my_dog.sit()
文章浏览阅读1.6w次,点赞8次,收藏41次。生活中我们无时不刻不都要在网站搜索资源,但就是缺少一个趁手的资源搜索网站,如果有一个比较好的资源搜索网站可以帮助我们节省一大半时间!今天小编在这里为大家分享5款超厉害的资源搜索网站,每一款都可以让你的资源丰富精彩!网盘传奇一款最有效的网盘资源搜索网站你还在为找网站里面的资源而烦恼找不到什么合适的工具而烦恼吗?这款网站传奇网站汇聚了4853w个资源,并且它每一天都会持续更新资源;..._最全资源搜索引擎
文章浏览阅读4.5k次,点赞5次,收藏18次。阅读测试程序,设计一个Book类。函数接口定义:class Book{}该类有 四个私有属性 分别是 书籍名称、 价格、 作者、 出版年份,以及相应的set 与get方法;该类有一个含有四个参数的构造方法,这四个参数依次是 书籍名称、 价格、 作者、 出版年份 。裁判测试程序样例:import java.util.*;public class Main { public static void main(String[] args) { List <Book>_6-1 book类的设计java
文章浏览阅读613次,点赞28次,收藏27次。相比于以前的传统手工管理方式,智能化的管理方式可以大幅降低学校的运营人员成本,实现了校园导航的标准化、制度化、程序化的管理,有效地防止了校园导航的随意管理,提高了信息的处理速度和精确度,能够及时、准确地查询和修正建筑速看等信息。课题主要采用微信小程序、SpringBoot架构技术,前端以小程序页面呈现给学生,结合后台java语言使页面更加完善,后台使用MySQL数据库进行数据存储。微信小程序主要包括学生信息、校园简介、建筑速看、系统信息等功能,从而实现智能化的管理方式,提高工作效率。
传统上用户登陆状态会以 Session 的形式保存在服务器上,而 Session ID 则保存在前端的 Cookie 中;而使用 JWT 以后,用户的认证信息将会以 Token 的形式保存在前端,服务器不需要保存任何的用户状态,这也就是为什么 JWT 被称为无状态登陆的原因,无状态登陆最大的优势就是完美支持分布式部署,可以使用一个 Token 发送给不同的服务器,而所有的服务器都会返回同样的结果。有状态和无状态最大的区别就是服务端会不会保存客户端的信息。
文章浏览阅读784次。发表于10小时前| 2674次阅读| 来源TechCrunch| 19 条评论| 作者Jon EvansiOSAndroid应用开发产品编程语言JavaObjective-C摘要:即便Android市场份额已经超过80%,对于开发者来说,使用哪一个平台做开发仍然很难选择。本文从开发环境、配置、UX设计、语言、API、网络、分享、碎片化、发布等九个方面把Android和iOS_ios 开发角度
搜索引擎的发展历史可以追溯到20世纪90年代初,随着互联网的快速发展和信息量的急剧增加,人们开始感受到了获取和管理信息的挑战。这些阶段展示了搜索引擎在技术和商业模式上的不断演进,以满足用户对信息获取的不断增长的需求。
文章浏览阅读990次。对象特性是指控制对象的输出参数和输入参数之间的相互作用规律。放大系数K描述控制对象特性的静态特性参数。它的意义是:输出量的变化量和输入量的变化量之比。时间常数T当输入量发生变化后,所引起输出量变化的快慢。(动态参数) ..._控制对象特性
文章浏览阅读5.7w次,点赞50次,收藏276次。FRP搭建内网穿透1.概述:frp可以通过有公网IP的的服务器将内网的主机暴露给互联网,从而实现通过外网能直接访问到内网主机;frp有服务端和客户端,服务端需要装在有公网ip的服务器上,客户端装在内网主机上。2.简单的图解:3.准备工作:1.一个域名(www.test.xyz)2.一台有公网IP的服务器(阿里云、腾讯云等都行)3.一台内网主机4.下载frp,选择适合的版本下载解压如下:我这里服务器端和客户端都放在了/usr/local/frp/目录下4.执行命令# 服务器端给执_locyanfrp
文章浏览阅读687次。题目:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=93745#problem/A题意:给出r*c的01矩阵,可以翻转格子使得0表成1,1变成0,求出最小的步数使得每一行中1的个数相等,每一列中1的个数相等。思路:网络流。容量可以保证每一行和每一列的1的个数相等,费用可以算出最小步数。行向列建边,如果该格子是_uva12534
文章浏览阅读504次。1、Let's Encrypt 90天,支持泛域名2、Buypass:https://www.buypass.com/ssl/resources/go-ssl-technical-specification6个月,单域名3、AlwaysOnSLL:https://alwaysonssl.com/ 1年,单域名 可参考蜗牛(wn789)4、TrustAsia5、Alpha..._csdn alphassl免费申请
文章浏览阅读1.6k次。测试算法的性能 很多时候我们需要对算法的性能进行测试,最简单的方式是看算法在特定的数据集上的执行时间,简单的测试算法性能的函数实现见testSort()。【思想】:用clock_t计算某排序算法所需的时间,(endTime - startTime)/ CLOCKS_PER_SEC来表示执行了多少秒。【关于宏CLOCKS_PER_SEC】:以下摘自百度百科,“CLOCKS_PE_算法性能测试
文章浏览阅读1.2k次。fromhttps://towardsdatascience.com/finding-lane-lines-simple-pipeline-for-lane-detection-d02b62e7572bIdentifying lanes of the road is very common task that human driver performs. This is important ..._lanedetectionlite