Python_嵌套

/ Python / 没有评论 / 655浏览

嵌套上场了

有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这成为嵌套 可以在列表中嵌套字典,在字典中嵌套列表甚至在字典中嵌套字典

字典列表

示范1

[root@pa1 lijinghua]#python qiantai.py
{'color': 'green', 'speed': 'slow'}
{'color': 'green', 'speed': 'slow'}
{'color': 'green', 'speed': 'slow'}
{'color': 'green', 'speed': 'slow'}
{'color': 'green', 'speed': 'slow'}
...
Total number of aliens :30
[root@pa1 lijinghua]#cat qiantai.py
#!/usr/local/python
aliens=[]
for aliens_number in range(30):
	new_alien={'color':'green','speed':'slow'}
	aliens.append(new_alien)
for alien in aliens[:5]:
	print(alien)
print("...")
print("Total number of aliens :"+ str(len(aliens)))

示范2(可以更改字典)

[root@pa1 lijinghua]#python qiantao.py
{'color': 'yellow', 'points': '10', 'speed': 'fast'}
{'color': 'yellow', 'points': '10', 'speed': 'fast'}
{'color': 'yellow', 'points': '10', 'speed': 'fast'}
{'color': 'yellow', 'points': '10', 'speed': 'fast'}
{'color': 'blue', 'points': '5', 'speed': 'slow'}
....
[root@pa1 lijinghua]#cat  qiantao.py
#!/usr/local/python
# -*- coding: utf-8 -*-
aliens=[]
for new_aliens in range(30):                  #循环30次
        new_aliens={
                'color':'blue',
                'points':'5',
                'speed':'slow',
                }
        aliens.append(new_aliens)
#	print(aliens)
for alien in aliens[:4]:                      #拿出前四个
        if alien['color'] =='blue':
		alien['color']='yellow'       #注意这里格式,就是这么直接改的
                alien['points']='10'
                alien['speed']='fast'
for alien in aliens[:5]:
	print(alien)                          #这里咋们试验下,打印5行,因为前面只改了四行,所有第五行会发现没有变动
print("....")

在字典中存储列表

有时候,需要将列表存在字典中,而不是将字典存在列表中 单词 topping = 糕点上的装饰配料 crust = 外壳 thick = 厚的 粗的 mushrooms = 蘑菇

示范

[root@pa1 lijinghua]#python zidian_list.py
You ordered a thick-crustwith the following:
	mushrooms
	extra cheese
[root@pa1 lijinghua]#cat zidian_list.py
#!/usr/local/python
pizza={
	'crust':'thick',
	'toppings':['mushrooms','extra cheese'],            #重点语法格式
	}
print("You ordered a " + pizza['crust']+"-crust"+"with the following:" )
for topping in pizza['toppings']:
	print("\t"+topping)

注意: 列表和字典的嵌套层级不应太多,如果嵌套层级比前面的示例多,意味着很可能有更简单的方案

在字典中存储字典

示范

[root@pa1 lijinghua]#python  zidian_zidian.py

Username: lijinghua
	 full_name: Jinghuali
	 location: Yuncheng

Username: niecongcong
	 full_name: Congcongnie
	 location: Huoxing
[root@pa1 lijinghua]#cat zidian_zidian.py
#!/usr/local/python
# -*- coding: utf-8 -*-
user={
	'lijinghua':{
		'first':'jinghua',
		'last':'li',
		'location':'yuncheng',
		},                            #注意这里的逗号
	'niecongcong':{
		'first':'congcong',
		'last':'nie',
		'location':'huoxing',
		}
	}


for nameuser,name_info in user.items():
	print("\nUsername: "+nameuser)
	full_name=name_info['first']+name_info['last']
	location=name_info['location']
	print("\t full_name: "+full_name.title())
	print("\t location: "+location.title())