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

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

问题描述

我想将字典添加到列表中,但是得到的结果不是我想要的.

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天全站免登陆