案例1
item1 = {}
gender_areas = []
for ge in gender:
# 男性
man = ge.split(":")[0].strip() or ''
# print("man",man)
# 男性比例
man_percent = ge.split(":")[1].strip() or ''
# print("man_percent",man_percent)
item1["man"] = man
item1["man_percent"] = man_percent
print(item1)
gender_areas.append(item1)
print("gender_areas", gender_areas)
运行结果:
全是女性,每次都是赋值最后一个字典
gender_areas [{‘gender_area’: ‘性别分布’, ‘man’: ‘女性’, ‘man_percent’: ‘13.46%’}, {‘gender_area’: ‘性别分布’, ‘man’: ‘女性’, ‘man_percent’: ‘13.46%’}]
解决方法1.
把item1 = {} 移到循环句里面,即可.
gender_areas = []
for ge in gender:
item1 = {}
# 男性
man = ge.split(":")[0].strip() or ''
# print("man",man)
# 男性比例
man_percent = ge.split(":")[1].strip() or ''
# print("man_percent",man_percent)
item1["man"] = man
item1["man_percent"] = man_percent
print(item1)
gender_areas.append(item1)
print("gender_areas", gender_areas)
运行结果正确:
gender_areas [{‘gender_area’: ‘性别分布’, ‘man’: ‘男性’, ‘man_percent’: ‘86.54%’}, {‘gender_area’: ‘性别分布’, ‘man’: ‘女性’, ‘man_percent’: ‘13.46%’}]
解决方法2.使用浅拷贝
def func():
...
yield result
list = []
for dic in func():
list.append(dic.copy())
原创文章,作者:,如若转载,请注明出处:https://blog.ytso.com/274780.html