【问题标题】:Is there a way to extract a key from a dictionary by using a filtering method有没有办法通过使用过滤方法从字典中提取键
【发布时间】: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


【解决方案1】:

我写的方法不正确,没有返回任何结果,如上所述。

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)

【讨论】:

    猜你喜欢
    • 2021-08-02
    • 2020-12-13
    • 2021-08-26
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 2022-06-17
    相关资源
    最近更新 更多