Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么是Python;附加“;行为不符合预期吗?_Python_List_Append - Fatal编程技术网

为什么是Python;附加“;行为不符合预期吗?

为什么是Python;附加“;行为不符合预期吗?,python,list,append,Python,List,Append,我有一段代码,我正在使用它将一个字典(其结构中有一个列表)转换为一个字典列表,在一个平面结构中为内部列表的每一项添加新的列。这是我的代码: origin = { "a":1, "b":2, "m":[ {"c":3}, {"c":4} ] } # separating the "flat" part of

我有一段代码,我正在使用它将一个字典(其结构中有一个列表)转换为一个字典列表,在一个平面结构中为内部列表的每一项添加新的列。这是我的代码:

origin = {
    "a":1,
    "b":2,
    "m":[
        {"c":3},
        {"c":4}
    ]
}
    
# separating the "flat" part of the structure
flat = dict()
for o in origin.keys():
    if not isinstance(origin[o], list):
        flat[o] = origin[o]

lines = list()
# starts receiving the 'flat' value, once the new lines will receive the same flat values.
new_line = flat

# getting the "non-flat" values and creating new dictionaries using the flat structure
for i in origin["m"]:
    k = list(i.keys())[0]
    v = list(i.values())[0]
    new_line[k] = v
    print(f"NEW_LINE: {str(new_line)}")
    lines.append(new_line)

print(f"LINES:\n{str(lines)}")
我期待着:

NEW_LINE: {'a': 1, 'b': 2, 'c': 3}
NEW_LINE: {'a': 1, 'b': 2, 'c': 4}
LINES:
[{'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 4}]
NEW_LINE: {'a': 1, 'b': 2, 'c': 3}
NEW_LINE: {'a': 1, 'b': 2, 'c': 4}
LINES:
[{'a': 1, 'b': 2, 'c': 4}, {'a': 1, 'b': 2, 'c': 4}]
但我明白了:

NEW_LINE: {'a': 1, 'b': 2, 'c': 3}
NEW_LINE: {'a': 1, 'b': 2, 'c': 4}
LINES:
[{'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 4}]
NEW_LINE: {'a': 1, 'b': 2, 'c': 3}
NEW_LINE: {'a': 1, 'b': 2, 'c': 4}
LINES:
[{'a': 1, 'b': 2, 'c': 4}, {'a': 1, 'b': 2, 'c': 4}]

为什么?

您需要将
字典
对象的副本追加为
行。追加(new\u line.copy())
,否则它们都指向同一个对象

请注意,
copy()
对对象进行浅层复制,您需要对嵌套对象使用
deepcopy()

请在中阅读两者之间的差异

浅复制和深复制之间的区别仅与 复合对象(包含其他对象的对象,如列表或 类实例):

  • 浅复制构造一个新的复合对象,然后(到 (可能的范围)在其中插入对中找到的对象的引用 原著

  • 深度复制构造一个新的复合对象,然后递归地, 将在原始文件中找到的对象的副本插入其中


您需要附加一个dict的
副本
:lines.append(new_line.copy()),否则它们都指向同一个对象。非常感谢@KrishnaChaurasia!