社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python3字典列表

huang cheng • 4 年前 • 1856 次点击  

在处理python3中的词典列表时,我遇到了一个奇怪的现象

oldlist = [{'name':'cheng'}]
ages = '18,20'
newlist = []

for ele in oldlist:
    for age in ages.split(','):
       ele['age'] = age
       newlist.append(ele)

print(newlist)

The result is :
[{'name': 'cheng', 'age': '20'}, {'name': 'cheng', 'age': '20'}]

What I am expected is 
[{'name': 'cheng', 'age': '18'}, {'name': 'cheng', 'age': '20'}]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129995
文章 [ 1 ]  |  最新文章 4 年前
enke
Reply   •   1 楼
enke    4 年前

那是因为 ele 仍在下一次迭代中引用同一词典。你需要创建一个副本。一种方法是把它抛给一条格言:

for ele in oldlist:
    for age in ages.split(','):
        ele['age'] = age
        newlist.append(dict(ele))

或者更好的是,不要使用 oldlist ,只需使用 埃勒 自身进行初始化:

ele = {'name':'cheng'}

for age in ages.split(','):
    ele['age'] = age
    newlist.append(ele)

输出:

[{'name': 'cheng', 'age': '18'}, {'name': 'cheng', 'age': '20'}]