附加到 Python 中的列表:每次都添加最后一个元素? [英] Appending to a list in Python: adds last element every time?

查看:48
本文介绍了附加到 Python 中的列表:每次都添加最后一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在列表中附加一个 dict,但得到的结果不是我想要的.

I want to append a dict to a list, but the result I'm getting isn't what I want.

我的代码:

records=[]
record={}
for i in range(0,2):
  record['a']=i  
  for j in range (0,2):
    record['b']=j
    records.append(record)
print records 

我期望:

[{'a': 0, 'b': 0}, {'a': 0, 'b': 1}, {'a': 1, 'b': 0}, {'a': 1, 'b': 1}]

我得到了:

[{'a': 1, 'b': 1}, {'a': 1, 'b': 1}, {'a': 1, 'b': 1}, {'a': 1, 'b': 1}]

为什么每次只添加最后一个元素?

Why is it only adding the last element every time?

推荐答案

您正在重复使用和添加一个字典.如果您想要单独的词典,请每次附加一个副本:

You are reusing and adding one single dictionary. If you wanted separate dictionaries, either append a copy each time:

records = []
record = {}
for i in range(2):
    record['a'] = i  
    for j in range(2):
        record['b'] = j
        records.append(record.copy())

或者每次创建一个新字典:

Or create a new dictionary each time:

records = []
for i in range(2):
    for j in range(2):
        record = {'a': i, 'b': j}
        records.append(record)

后一种方法适用于转换为列表理解:

The latter approach lends itself to translation to a list comprehension:

records = [{'a': i, 'b': j} for i in range(2) for j in range(2)]

这篇关于附加到 Python 中的列表:每次都添加最后一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆