在Python中,字典用放在花括号{}中的一系列键—值对表示,如前面的示例所示:
字典:
alien_0 = {'color': 'green', 'points': 5}
创建一个空字典:
alien_0 = {}
增加键值对
alien_0 = {}
alien_0['x_position'] = 0 9
alien_0['y_position'] = 25
{'y_position': 25, 'x_position': 0}
修改键值对:
alien_0 = {'color': 'green'}
alien_0['color'] = 'yellow'
删除键—值对
alien_0 = {'color': 'green', 'points': 5}
del alien_0['points']
遍历所有的键—值对
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi'
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
Key: last
Value: fermi
Key: first
Value: enrico
Key: username
Value: efermi
方法items()
它返回一个键—值对列表。接下来, for循环依次将每个键—值对存储到指定的两个变量中,键—值对的返回顺序也与存储顺序不同
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +language.title() + ".")
Jen's favorite language is Python.
Sarah's favorite language is C.
Phil's favorite language is Python.
Edward's favorite language is Ruby.
遍历字典中的所有键 方法keys() values() 只打印键或者值
favorite_languages = {
'jen': 'python',
'sarah': 'c', 'edward':
'ruby', 'phil':
'python', }
for name in favorite_languages.keys():
print(name.title())
for name in favorite_languages.values():
print(name.title())
sorted()
要以特定的顺序返回元素,一种办法是在for循环中对返回的键进行排序。为此
可使用函数sorted()来获得按特定顺序排列的键列表的副本
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
为剔除重复项,可使用集合(set)。 集合类似于列表,但每个元素都必须是独一无二的
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
嵌套
有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。你 可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。正如下面的示例将演示的,
嵌套是一项强大的功能
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)
在字典中存储列表
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 a thick-crust pizza with the following toppings:
mushrooms
extra cheese
字典嵌套列表
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title())
Jen's favorite languages are:
Python
Ruby
Sarah's favorite languages are:
C
Edward's favorite languages are:
Ruby
Go
Phil's favorite languages are:
Python
Haskell
字典嵌套字典:
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()
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在 一个变量中,以方便你使用
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
有时候,提示可能超过一行,例如,你可能需要指出获取特定输入的原因。在这种情况下, 可将提示存储在一个变量中,再将该变量传递给函数input()。这样,即便提示超过一行,input() 语句也非常清晰
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")
使用int()来获取数值输入 使用函数input()时,Python将用户输入解读为字符串
例子:
gaodu = input("ni you duo gao ?")
gaodu = int(gaodu)
if gaodu >= 150:
print("ke yi jin qu")
else:
print("bu ke yi jin qu")
%去余,判断偶数或者奇数
shuzi = input("shu ru yi ge shu zi:")
shuzi = int(shuzi)
if shuzi %2 == 0 :
print("ni shu ru shi de yi ge ou shu")
else :
print("ni shu ru de shi ji shu")
while循环
a = 1
while a <= 5 :
print(a)
a = a + 1
让用户选择何时退出
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)
print(message)
使用标志
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于 活动状态。这个变量被称为标志,充当了程序的交通信号灯。你可让程序在标志为True时继续运 行,并在任何事件导致标志的值为False时让程序停止运行。这样,在while语句中就只需检查一 个条件——标志的当前值是否为True,并将所有测试(是否发生了应将标志设置为False的事件) 都放在其他地方,从而让程序变得更为整洁
如 a = True
使用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() + "!")
在循环中使用continue
num = 0
while num < 10:
num = num +1
if num %2 == 1:
continue
print(num)21
在列表之间移动元素
假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户后,如何将他们移 到另一个已验证用户列表中呢?一种办法是使用一个while循环,在验证用户的同时将其从未验 证用户列表中提取出来,再将其加入到另一个已验证用户列表中
wei_user = ["a" , "b" , "c"]
yanzhengguode = []
while wei_user :
yanzheng = wei_user.pop()
print("yan zheng yong hu :" + yanzheng.title())
yanzhengguode.append(yanzheng)
print("\n yan zheng de suo you yong hu :")
for yanzhengsuoyou in yanzhengguode :
print(yanzhengsuoyou.title())
结果为:
yan zheng yong hu :C
yan zheng yong hu :B
yan zheng yong hu :A
yan zheng de suo you yong hu :
C
B
A
删除包含特定值的所有列表元素
假设你有一个宠物列表,其中包含多个值为'cat'的元素。要删除所有这些元素,可不断运 行一个while循环,直到列表中不再包含值'cat'
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
结果:
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
使用用户输入来填充字典
可使用while循环提示用户输入任意数量的信息。下面来创建一个调查程序,其中的循环每 次执行时都提示输入被调查者的名字和回答。我们将收集的数据存储在一个字典中,以便将回答 同被调查者关联起来
a = {}
a_pd = True
while a_pd :
name = input("\n你叫啥?")
b = input("你最喜欢谁?")
a[name] = b
c = input("谁还接受调查?( yes / no )")
if c == 'no' :
a_pd = False
print("----调查结果-----")
for name , a in a.items() :
print(name + "最喜欢的是:" + a)
结果:
你叫啥?小金
你最喜欢谁?小吴
还有吗?( yes / no )no
----调查结果-----
小金最喜欢的是:小吴