gpt4 book ai didi

python - 列表的 UserDict

转载 作者:行者123 更新时间:2023-12-01 02:47:02 26 4
gpt4 key购买 nike

我相信我犯了一个我找不到的小误解。基本上,我正在设计一个简单的数据容器来保存 {key1:[values1], key2:[values2]}。

class Cells(object):
def __init__(self, **kwargs):
self.data = {}

def __data_len__(self):
""" Length of data[first key] list. """
_ = 0
for key in self.data.keys():
if self.data[key]:
_ = len(self.data[key])
break
return _

def subtract_lists(self, x, y):
return [item for item in x if item not in y]

def add(self, to_add):
""" Add columns if not exist """
if not set(to_add.keys()).issubset(self.data.keys()): # New key means adding
new_keys = self.subtract_lists(to_add.keys(), \
self.data.keys()) # it to our dict
newdict = dict.fromkeys(new_keys, \
[] * self.__data_len__())
self.data.update(newdict)

[self.data[key].append(to_add.get(key, '')) for key in self.data.keys()]
print('* Updated data is: %s' % self.data)

##############################
# Now, tests... #
##############################
if __name__ == '__main__':
cells = Cells()
cells.add({'one':1, 'two':2, 'three': 3})

期望的输出是这样的:

Updated data is: {'one': [1], 'two': [2], 'three': [3]}

但它输出:

Updated data is: {'one': [1, 2, 3], 'two': [1, 2, 3], 'three': [1, 2, 3]}

即将每个值添加到每个键,这令人沮丧。某处打字错误?

最佳答案

问题是您将 newdict 中的所有值分配为相同的空列表。有关相关行为的说明,请参阅此处:Python initializing a list of lists 。该值仅被评估一次,并且字典中的所有值都存储相同的列表对象。

顺便说一句,[] * n(对于任何n)仍然只是[]

更改此行:

    newdict = dict.fromkeys(new_keys, \
[] * self.__data_len__())

对此:

    newdict = {key: [] for key in new_keys}

关于python - 列表的 UserDict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45156555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com