我设置了一个集合类,并创建了一个包含字典的对象。 我创建了一个称为pluck(self,key)的方法,该方法应该返回一个新的Collection,其中包含我发送的所有键的值,并且我使用了之前创建的另一个方法(map和filter-两种collection方法)。
类集合(对象):
def __init__(self,iterable = None):
# param iterable: imutable collection
if iterable == None:
self.Iterable = ()
else:
self.Iterable = tuple(iterable)
return None
def map(self, *callbacks):
'''
:param callbacks: List of function to apply on each element in 'self.Iterable'
:return: New mapped collection
'''
c =Collection(self.Iterable)
tmp = Collection()
for item in callbacks:
for item2 in c.Iterable:
tmp = tmp.append(item(item2))
c = Collection(tmp.Iterable)
return c
def filter(self, *callbacks):
'''
:param callbacks: List of function to apply on each element in 'self.Iterable'
:return: New filtered collection
'''
return Collection(item for item in self.Iterable if CallbacksFilter(item, callbacks) == True)
def CallbacksFilter(item, callback):
for f in callback:
if f(item) == False:
return False
return True
当我尝试运行采摘方法时:
def pluck(self, key):
return self.values() if type(self.first()) is not dict else Collection(self.Iterable).filter(self.map(lambda x, y: dict([(i,x[i]) for i in x if i in set(y)])))
c3 = Collection([{'name': 'Joe', 'age': 20}, {'name': 'Jane', 'age': 13}])
c3.pluck('age')
我希望输出“ Collection(20,13)”,但出现此错误:
TypeError:()缺少1个必需的位置参数:“ y”
如何解决此错误?
注意:如果内部元素不是字典,则返回当前集合的副本。
答案 0 :(得分:0)
如上所述,我编写的方法不正确,不会返回任何结果。
def pluck(self, key):
return self.values() if type(self.first()) is not dict else Collection(self.Iterable).filter(self.map(lambda x, y: dict([(i,x[i]) for i in x if i in set(y)])))
Map方法通过在集合的每个字典上应用赋予它的lambda函数来返回结果。
def map(self, *callbacks):
'''
:param callbacks: List of function to apply on each element in 'self.Iterable'
:return: New mapped collection
'''
c =Collection(self.Iterable)
tmp = Collection()
for item in callbacks:
for item2 in c.Iterable:
tmp = tmp.append(item(item2))
c = Collection(tmp.Iterable)
return c
因此,当我们运行以下代码时:
def pluck(self, key):
'''
:param key: Dictionary key (13)
:return: Return a new Collection with value of each key.
'''
return "Collection{}".format(Collection(self.map(lambda index: index[key])).Iterable)
c3 = Collection([{'name': 'Joe', 'age': 20}, {'name': 'Jane', 'age': 13}])
c3.pluck('age')
我们得到正确的结果:
收藏(20,13)