0

在 Week 类中,我使用 .fromkey() 方法创建了一个字典,其中包含周一至周六的字符串键,并将它们全部初始化为一个空列表:

self.weekDict = dict.fromkeys(dayNameList, [])

我有一个函数,然后迭代一个员工列表,并且在每次迭代中,迭代他们的工作日并将员工附加到每天的相应 weekDict 列表中:

def setWeekDict(employees):
            for employee in employees:
                for day in employees[employee].workDays:
                    self.weekDict[day].append(employee)
                    print "employee: " + employee
                    print "weekday/list: " + str(day) + str(self.weekDict[day])

我希望 weekDict 列表能够反映计划在特定日期工作的每个人。相反,似乎每天的列表都会累积我每天为员工迭代的总次数。我的打印语句输出如下:

employee: Addison
weekday/list: Saturday['Addison']
employee: Addison
weekday/list: Monday['Addison', 'Addison']
employee: Addison
weekday/list: Tuesday['Addison', 'Addison', 'Addison']
employee: Addison
weekday/list: Wednesday['Addison', 'Addison', 'Addison', 'Addison']
employee: Addison
weekday/list: Thursday['Addison', 'Addison', 'Addison', 'Addison', 'Addison']

显然,我只希望“Addison”或任何其他员工每天出现一次,而且我无法理解我的 for 循环中的内容会为每个列表添加员工姓名 + 员工姓名被添加到的次数之前的其他列表。我只能认为 dict.fromkeys() 创建的键实际上都指向同一个列表,但我不认为 fromkeys() 函数是这样工作的。

4

1 回答 1

2

fromkeys()如果与可变对象一起使用可能会导致这种行为,因为它将相同的对象(相同id())分配给字典的每个键。

In [16]: dic=dict.fromkeys("spam",[])

In [17]: [id(x) for x in dic.values()]    #all of them are same objects
Out[17]: [141885196, 141885196, 141885196, 141885196]

In [18]: dic['s'].append(1)   #changing one changes others as well

In [19]: dic
Out[19]: {'a': [1], 'm': [1], 'p': [1], 's': [1]}

因此,dict-comprehensions必须与可变对象一起使用:

In [20]: dic={x:[] for x in "spam"}

In [21]: [id(x) for x in dic.values()]               #unique objects
Out[21]: [141884972, 141848300, 142262988, 141895980]

In [22]: dic['s'].append(1)

In [23]: dic
Out[23]: {'a': [], 'm': [], 'p': [], 's': [1]}
于 2013-01-10T19:47:09.943 回答