字典用花括号({ })来存储信息。
alien_0={'color':'green','points':5} print(alien_0['color'])#访问字典中的值 print(alien_0['points'])#访问字典中的值运行结果:
green 5字典中的color和points都是键,green和5都是值,键与值之间用冒号(:)连接。
访问字典中的值添加键-值对 alien_0={'color':'green','points':5} print(alien_0) alien_0['x_position']=0 alien_0['y_position']=25 print(alien_0)运行结果:
{'color':'green','points':5} {'color':'green','points':5,'y_position':25, 'x_position':0}键-值对的排列顺序与添加顺序不同。Python不必关心键-值对的添加顺序,而只关心键和值之间的关联关系。
创建一个空字典 alien_0={} alien_0['color']='green' alien_0['points']=5 print(alien_0)运行结果:
{'color':'green','points':5} 修改字典中的值 alien_0={'x_position':0,'y_position':25,'speed':'medium'} print("Original X-position:"+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']))运行结果:
Original x-position:0 New x-position:2 删除键-值对使用del语句。 必须指定字典名和要删除的键。
alien_0={'color':'green','points':5} print(alien_0) del alien_0['points'] print(alien_0)运行结果:
{'color':'green','points':5} {'color':'green'}删除的键-值对永远消失了。
由类似对象组成的字典运行结果:
Key:last Value:fermi Key:first Value:enrico Key:username Value:efermi即便遍历字典时,键-值对得返回顺序也与存储顺序不同。python不关心键-值对的存储顺序,而只跟踪键和值的关联关系。
遍历字典中的所有键 for name in favorite_languages.keys():遍历字典时,会默认遍历所有的键,因此可以写成下面的形式,输出将不变。
for name in favorite_languages: 按顺序遍历字典中的所有键可使用函数sorted()来获得按特定顺序排列的键列表的副本。
for name in sorted(favorite_languages.keys()) 遍历字典中的所有值 for name in favorite_languages.values():这种做法提取字典中所有的值,可能包含了大量的重复项。 通过对包含重复元素的列表调用set(),可以让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合。
for language in set(favorite_language.value())将一系列字典存储再列表中,或将列表作为值存储在字典中,这称为嵌套。
字典列表 把字典存储在列表中。 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} 在字典中存储列表 把列表存储在字典中。 pizza={ 'crust':'thick', 'toppings':['mushroons','extre cheese'] } print("You ordered a"+pizza['crust']+"-crust pizza"+ "with the following toppings:") for topping in pizza['topping']: print("\t"+topping)运行结果:
You ordered a thick-crust pizza with the following toppings: mushroons extra cheese每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表。
在字典中存储字典 users={ 'aeinstein':{'username':'efermi', 'first':'enrico', 'last':'fermi', } 'mcurie':{'username':'marie', 'first':'curie', 'last':'paris', } } for username,user_info in users.items(): print("\nUsername":+username) full_name=user_info['first']+" "+user_info['last'] location=user_info['location'] print("\fullname:":+full_name.title()) print("\location:":+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! 使用int()来获取数值输入 当使用input()来获取数字时,Python会将输入解读为字符串而不是数字,如果想要被当作数字来处理,则需要使用int()。 age=input("How old are you?")运行结果:
How old are you?21 age=int(age) age>=18运行结果:
True 求模运算符 求模运算符:%,将两个数相除并返回余数for循环用于针对集合中的每个元素的每一个代码块,而while循环不断地进行,直到指定的条件不满足为止。
使用while循环 current_number=1 while current_number<=5: print(current_number) current_number+=1运行结果:
1 2 3 4 5 让用户选择何时退出 prompt="\nTell me something,and I will repeat it back to you:" prompt+="\nEnter 'quit' to end the program." message="" while message != 'quit': message = input(prompt) if message != 'quit': print(message)运行结果:
Tell me something,and I will repeat it back to you: Enter 'quit' to end the program.Helo everyone! Helo everyone! Tell me something,and I will repeat it back to you: Enter 'quit' to end the program.quit 使用标志 在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志,充当了程序的交通信号灯。可以让程序在标志为True时继续运行,并在任何实践导致标志为False时让程序停止运行。 这样,在while语句中就只需检查一个条件——标志的当前值是否为True。 prompt="\nTell me something,and I will repeat it back to you:" prompt+="\nEnter 'quit' to end the program." active = True while active message = input(prompt) if message == 'quit': active=False else: print(message) 使用break退出循环 prompt="\nPlease inter 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()+"!")运行结果:
Please inter the name of a city you have visited: (Enter 'quit' when you are finished.)New York I'd love to go to New York! Please inter the name of a city you have visited: (Enter 'quit' when you are finished.)quit在任何Python循环中都可使用break语句。例如,可使用break语句来退出遍历列表或字典的for循环。
在循环中使用continue 要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句。 current_number=0 while current_number<10: current_number+=1 if current_number%2==0: continue print(current_number)如果当前的数字不能被2整除,就执行循环中余下的代码。 运行结果:
1 3 5 7 9 避免无限循环 每个while循环都必须要有停止运行的途径。for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可手机、存储并组织大量输入,供以后查看和显示。
在列表之间移动元素 #首先,创建一个待验证用户列表 # 和一个用于存储已验证用户的空列表 unconfirmed_users=['alice','brian','candace'] confirmed_users=[] #验证每个用户,直到没有未验证用户为止 # 将每个经过验证的列表都移到已验证用户列表中 while unconfirmed_users: current_user=unconfirmed_user.pop() print("Verify user:"+current_user.title()) confirmed_user.append(current_user) #显示所有已验证的永华 print("\nThe following users have been confirmed:") for confirmed_user in confirmed_ussers: print(confirmed_user.title())运行结果:
Verifying user:Candace Verifying user:Brian Verifying user:Alice The following users have been confirmed: Candace Brian Alice 删除包含特定值的所有列表元素 使用方法remove()来删除列表中的特定值。 加入有一个宠物列表,其中包含多个‘cat’的元素。要删除所有这些元素,可不断运行一个while循环,直到列表中不再包含’cat’。 pets=['dog','cat','dog','goldfis','cat','rabbit','cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)运行结果:
['dog','cat','dog','goldfis','cat','rabbit','cat'] ['dog','dog','goldfis','rabbit']首先创建了一个列表,其中包含多个值为’cat’的元素。打印这个列表后,Python进入while循环,因为它发现’cat’在列表中至少出现了一次。进入循环后,Python删除第一个’cat’并返回到while代码行,然后发现’cat’还包含在列表中,因此再次进入循环,直到这个值不包含在列表中。
使用用户输入来填充字典 response={} #设置一个标志,指出调查是否继续 polling_active=True while polling_active: #提示输入被调查者的名字和回答 name=input("\nWhat is your name?") response=input("Which mountain would you like to climb someday?") #将答卷存储在字典中 response[name]=response #看看是否还有人要参与调查 repeat=input("Would you like to let another person respond?(yes/no)") if rpeat=='no': polling_active=False #调查结束,显示结果 print("\n---Poll Results---") for name,response in response.items(): print(name+"would like to climb"+response+".")运行结果:
What is your name?Eric Which mountain would you like to climb someday?Denali Would you like to let another person respond?(yes/no)yes What is your name?Lynn Which mountain would you like to climb someday?Devil's Thumb Would you like to let another person respond?(yes/no)no ---Poll Results--- Lynn would like to climb Devil's Thumb. Eric would like to climb Denali.今天一连趟写了三篇学习笔记,这些都是之前学过的,无非是今天整理到csdn上来。本篇是今天学习的,并且对字典和while循环一直不太熟悉。因此在本篇中记录了很多书上给出的例子。后面大概会按部就班的继续学习,不过更新频率肯定没有今天这样了。读懂了还要去消化,并且还要学习matlab的一些知识。希望这半年可以完成自己想要做到的事情。
