[英]Unpack a list of dictionaries and set each to its own variable
所以我创建了一个作为参数的类,需要一个或多个字典。 然后它会初始化这些词典的列表。 我正在定义一个__add__()
方法,该方法接受此类的两个对象并返回一个新对象,该对象由第一个对象的字典组成,后跟第二个对象的字典。
class DictList:
def __init__(self, *d):
self.dl = []
for argument in d:
if type(argument) != dict:
raise AssertionError(str(argument) + ' is not a dictionary')
if len(argument) == 0:
raise AssertionError('Dictionary is empty')
else:
self.dl.append(argument)
例如,
d1 = DictList(dict(a=1,b=2), dict(b=12,c=13))
d2 = DictList(dict(a='one',b='two'), dict(b='twelve',c='thirteen'))
然后d1 + d2相当于
DictList({'a': 1, 'b': 2}, {'b': 12, 'c': 13}, {'a': 'one', 'b': 'two'}, {'b': 'twelve', 'c': 'thirteen'})
要一起添加两个列表,只需使用+
运算符即可。
要从一个dicts列表中创建一个对象而不是一堆单独的dict参数,只需使用*
来解压缩列表。
所以:
def __add__(self, other):
return type(self)(*(self.dl + other.dl))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.