[英]Unpack a list of dictionaries and set each to its own variable
So I am creating a class which as arguments, takes 1 or more dictionaries. 所以我创建了一个作为参数的类,需要一个或多个字典。 It then intializes a list of those dictionaries. 然后它会初始化这些词典的列表。 I am defining an __add__()
method that takes two objects of this class and returns a new object consisting of the dictionaries from the first object followed by those of the second object. 我正在定义一个__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)
For example, 例如,
d1 = DictList(dict(a=1,b=2), dict(b=12,c=13))
d2 = DictList(dict(a='one',b='two'), dict(b='twelve',c='thirteen'))
then d1+d2 would be equivalent to 然后d1 + d2相当于
DictList({'a': 1, 'b': 2}, {'b': 12, 'c': 13}, {'a': 'one', 'b': 'two'}, {'b': 'twelve', 'c': 'thirteen'})
To add two lists together, just use the +
operator. 要一起添加两个列表,只需使用+
运算符即可。
And to create one of your objects out of a list of dicts instead of a bunch of separate dict arguments, just use *
to unpack the list. 要从一个dicts列表中创建一个对象而不是一堆单独的dict参数,只需使用*
来解压缩列表。
So: 所以:
def __add__(self, other):
return type(self)(*(self.dl + other.dl))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.