peoples = [] ##创建人群的空列表
for people_s in range(30):##range()返回一系列数字,重复这个循环多次
new_people = {'name':'zhangsan','age':'25','city':'beijing'}##每次循环时,创建一个人物
peoples.append(new_people)##将其添加到列表末尾
for people in peoples[:5]:##使用切片打印出前五个人
print(people)
print('...')
print('The number of :',str(len(peoples)))##打印列表长度,以证实创建了30个人
{'name': 'zhangsan', 'age': '25', 'city': 'beijing'}
{'name': 'zhangsan', 'age': '25', 'city': 'beijing'}
{'name': 'zhangsan', 'age': '25', 'city': 'beijing'}
{'name': 'zhangsan', 'age': '25', 'city': 'beijing'}
{'name': 'zhangsan', 'age': '25', 'city': 'beijing'}
...
The number of : 30
>>>
这些人都叫相同的名字,年龄,城市,每个人都是独立的,可以独立的修改每个人。
在这里插入代码片peoples = []
for people_s in range(30):
new_people = {'name':'zhangsan','age':'25','city':'beijing'}
peoples.append(new_people)
for people in peoples[0:3]:
if people['name'] == 'zhangsan':
people['name'] = 'lisi'
people['age'] == '22'
people['city'] == 'shanghai'
for people in peoples[:5]:
print(people)
print('...')
print('The number of :',str(len(peoples)))
{'name': 'lisi', 'age': '25', 'city': 'beijing'}
{'name': 'lisi', 'age': '25', 'city': 'beijing'}
{'name': 'lisi', 'age': '25', 'city': 'beijing'}
{'name': 'zhangsan', 'age': '25', 'city': 'beijing'}
{'name': 'zhangsan', 'age': '25', 'city': 'beijing'}
...
The number of : 30
>>>
扩展循环,添加elif代码块,
peoples = []
for people_s in range(30):
new_people = {'name':'zhangsan','age':'25','city':'beijing'}
new_people2 = {'name':'lisi','age':'55','city':'shandong'}
peoples.append(new_people)
peoples.append(new_people2)
for people in peoples[0:10]:
if people['name'] == 'zhangsan':
people['name'] = 'lisi'
people['age'] = '22'
people['city'] = 'shanghai'
elif people['name'] == 'lisi':
people['name'] = 'wangwu'
people['age'] = '27'
people['city'] = 'guangzhou'
for people in peoples[:10]:
print(people)
print('...')
print('The number of :',str(len(peoples)))
{'name': 'lisi', 'age': '22', 'city': 'shanghai'}
{'name': 'wangwu', 'age': '27', 'city': 'guangzhou'}
{'name': 'lisi', 'age': '22', 'city': 'shanghai'}
{'name': 'wangwu', 'age': '27', 'city': 'guangzhou'}
{'name': 'lisi', 'age': '22', 'city': 'shanghai'}
{'name': 'wangwu', 'age': '27', 'city': 'guangzhou'}
{'name': 'lisi', 'age': '22', 'city': 'shanghai'}
{'name': 'wangwu', 'age': '27', 'city': 'guangzhou'}
{'name': 'lisi', 'age': '22', 'city': 'shanghai'}
{'name': 'wangwu', 'age': '27', 'city': 'guangzhou'}
...
The number of : 60
>>>
people = {
'police':{
'first':'zhang',
'last':'qiang',
'age':'24',
'city':'shanghai',
},
'doctor':{
'first':'liu',
'last':'ying',
'age':'23',
'city':'guangzhou',
},
}
for people_occupation, people_info in people.items():
print('\npeople_occupation:'+ people_occupation)
name = people_info['first']+''+people_info['last']
age_s = people_info['age']
city_s = people_info['city']
print('\tname:'+name)
print('\tage:'+age_s)
print('\tcity:'+city_s)
people_occupation:police
name:zhangqiang
age:24
city:shanghai
people_occupation:doctor
name:liuying
age:23
city:guangzhou
>>>