【发布时间】:2019-05-25 02:10:53
【问题描述】:
我设置了一个集合类,并创建了一个包含字典的对象。 我创建了一个名为 pluck(self, key) 的方法,它应该返回一个包含我发送的键的所有值的新 Collection,并且我使用了我之前创建的另一个方法(map 和 filter - 两种收集方法)。
类集合(对象):
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
当我尝试运行 pluck 方法时:
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'
我该如何解决这个错误?
注意:如果内部元素不是字典,则返回当前集合的副本。
【问题讨论】:
-
如果您有解决方案,您应该将其作为自己的答案发布,而不是将其包含在问题中。
标签: python-3.x dictionary filter collections key