编程语言
首页 > 编程语言> > Python for循环中添加字典到列表,结果列表中全是循环中的最后一个值

Python for循环中添加字典到列表,结果列表中全是循环中的最后一个值

作者:互联网

案例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())

标签:Python,gender,item1,percent,列表,循环,print,areas,man
来源: https://www.cnblogs.com/gqv2009/p/16484885.html