- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我相信我犯了一个我找不到的小误解。基本上,我正在设计一个简单的数据容器来保存 {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/
我相信我犯了一个我找不到的小误解。基本上,我正在设计一个简单的数据容器来保存 {key1:[values1], key2:[values2]}。 class Cells(object): de
使用 UserDict 类有什么好处? 我的意思是,如果不是 class MyClass(object): def __init__(self): self.a = 0
我想定义一个 UserDict 来从 JSON 读取值并存储给定键的位置。 JSON 文件如下所示: { "pages": [ { "areas": [
这个问题在这里已经有了答案: How to pickle and unpickle instances of a class that inherits from defaultdict? (2 个
我们代码库中的一些类继承自 UserDict 以充当 dict 对象。 我试图为它们应用一个元类,但我做不到,因为它们是旧式类。 那么,是否有我可以使用的新型 UserDict 版本? 最佳答案 您可
如果我希望一个类具有字典行为,为什么要继承dict 或UserDict? 最佳答案 你可以继承自dict在任何 2.2 版或更高版本的 Python 中,但您必须覆盖每一个感兴趣的方法——例如,您对
import unittest from UserDict import UserDict class MyDict(UserDict): def __init__(self, x):
UserDict、dict和ABC有什么区别,推荐哪一种?文档似乎已弃用 UserDict? 似乎 UserDict 的 update() 会使用我的 setitem 方法,而 dict 不会?鉴于我
UserDict Source Code UserDict 有__copy__ 和.copy() 方法。前者由copy.copy(x) 触发,后者由x.copy() 触发。在 copy() 中,它首先
今天编码,首选和推荐(在 Python 2 和 3 中)以上哪项用于子类化? 我读到引入了UserList和UserDict,因为以前list和dict不能被子类化,但既然这不再是问题,是否鼓励使用它
我是一名优秀的程序员,十分优秀!