(一).嵌套:需要将一系列字典存储在列表中,或者将列表作为值存储在字典中。我们来看一个简单的例程:将字典放入到字典当中并将其中的数据进行打印。
car1 = {'audi' : 'A6L'}
car2 = {'audi' : 'A4L'}
car3 = {'audi' : 'A8L'}
car = [car1, car2, car3]
for cars in car:
print(cars)
下面我们来看一个稍微复杂一些的程序,它使用了嵌套来进行数据的存储,并在输出的时候将我们的数据用for循环进行输出。
users = {
'aeinstein' : {
'first' : 'albert',
'last' : 'einstein',
'location' : 'princeton',
},
'mcurie' : {
'first' : 'marie',
'last' : 'curie',
'location' : 'paris',
},
}
for username, user_info in users.items():
print("\n Username:" + 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
上面的方法items(),他返回一个键值对列表,我们用for循环所建立的两个变量来进行键和值的存储,用户名’aeinstein’和’mcurie’与每个键相关联的值都是一个字典,其中包含用户的名,姓和居住地。
(二).用户输入
1.input()接受一个参数:既要向用户显示的提示或者说明,让用户知道该如何做。
我们可以使用 += 来进行一个字符串末尾附加一个字符串的操作
message = "Tell me something,and i will repeat it back to you"
message += "\nso,what do you want to say"
print(message)
我们可以得到如下的输出
Tell me something,and i will repeat it back to you
so,what do you want to say
为了便于观看,我们在第二个字符串之前加上了换行符。对于input()的输入,我们得到的只是字符串,即使我们输入的是数字,我们可以使用int()函数来获得数值输入
(三).while循环:
1.基本使用:
counts = 1
while counts <= 5:
message = "the count is "
print(message + str(counts))
counts += 1
同样,我们要注意while循环这一行最后的冒号
2.我们使用break来推出循环:break循环会使程序立刻退出while循环,不再执行循环中剩下的代码
counts = 1
while counts <= 5:
message = "the count is "
print(message + str(counts))
counts += 1
if counts == 4:
break
3.我们可以使用countinue语句让程序回到循环开头,并根据条件测试结果决定是否继续执行循环,例如,我们可以使用下面的代码让程序打印出3-11的奇数。
(四 ).使用while循环来处理列表和字典
1.for循环式遍历列表的有效的方式,但是for循环如果被用来修改列表,那么将导致python难以追踪其中的元素,因此,可使用while循环在遍历列表的同时修改列表的元素。
在该程序中,pop()函数以每次一个的方式从列表末尾删除未验证的用户,同样,我们可以使用remove()函数来删除列表中重复出现的值,代码如下:
pets = ['dog', 'dog', 'dog', 'duck']
print(pets)
while 'dog' in pets:
pets.remove('dog')
print(pets)
输出结果为
['dog', 'dog', 'dog', 'duck']
['duck']