首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >python字典在for循环中覆盖自己,这是不可能的。

python字典在for循环中覆盖自己,这是不可能的。
EN

Stack Overflow用户
提问于 2022-02-27 23:10:28
回答 1查看 38关注 0票数 0

我很难理解python函数为什么不输出带有附加的杂乱列表的字典,而是创建一个只包含最后创建的列表的字典。我已经重写了这个函数很多次,但是仍然遇到同样的问题。

代码语言:javascript
运行
复制
#simple schedule fitness test run
#imports
from itertools import permutations
import random
import numpy as np

#create teachers with classes and students with classes
brian_classes = ['akstuddies', 'sci_ms', 'sci_ms', 'physics', 'comp_sci', 'conf']
becky_classes = ['akstuddies', 'lit_ms', 'lit_ms', 'lit', 'conf', 'debate']
teachers = [brian_classes, becky_classes]
#creates inital population of n schedules by shuffling the schedule of each teacher n times
def initial_population(teachers_list, population_size):
    schudule_list_population = {}
    for i in range(0, population_size):
        shuffled_teachers = []
        schudule_list_population[i] = [teacher for teacher in teachers_list]
        for teacher in schudule_list_population[i]:
            np.random.shuffle(teacher)
            shuffled_teachers.append(teacher)
            #print(teacher)
        schudule_list_population[i] = shuffled_teachers
        print(schudule_list_population)
    return schudule_list_population

print(initial_population(teachers, 2))

output:

{0: [['akstuddies', 'conf', 'physics', 'sci_ms', 'sci_ms', 'comp_sci'], ['lit_ms', 'lit', 'conf', 'debate', 'lit_ms', 'akstuddies']]}

{0: [['sci_ms', 'physics', 'comp_sci', 'akstuddies', 'sci_ms', 'conf'], ['conf', 'lit_ms', 'lit_ms', 'akstuddies', 'debate', 'lit']], 1: [['sci_ms', 'physics', 'comp_sci', 'akstuddies', 'sci_ms', 'conf'], ['conf', 'lit_ms', 'lit_ms', 'akstuddies', 'debate', 'lit']]}

{0: [['sci_ms', 'physics', 'comp_sci', 'akstuddies', 'sci_ms', 'conf'], ['conf', 'lit_ms', 'lit_ms', 'akstuddies', 'debate', 'lit']], 1: [['sci_ms', 'physics', 'comp_sci', 'akstuddies', 'sci_ms', 'conf'], ['conf', 'lit_ms', 'lit_ms', 'akstuddies', 'debate', 'lit']]}
EN

回答 1

Stack Overflow用户

发布于 2022-02-27 23:16:09

我认为您希望python为您做一个深度复制,但默认情况下它不会,所以您需要多次存储相同的列表。下面是一个简单的例子

代码语言:javascript
运行
复制
In [1]: sub_list = [1,2,3,4]

In [2]: outer_list=[]

In [3]: outer_list.append(sub_list) # doesn't do a deep copy

In [4]: outer_list.append(sub_list) # doesn't do a deep copy

In [5]: outer_list
Out[5]: [[1, 2, 3, 4], [1, 2, 3, 4]]

In [6]: sub_list[0] = 10

In [7]: outer_list
Out[7]: [[10, 2, 3, 4], [10, 2, 3, 4]]

看看怎么真的只有一张单子?如果你想要一份深度拷贝,你可以做

代码语言:javascript
运行
复制
import copy
outer_list.append(copy.deepcopy(sub_list))

你那乱七八糟的老师名单只是被加到你的字典里好几次了,就像我在这里把它加到我的字典里一样。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71289202

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档