代码之家  ›  专栏  ›  技术社区  ›  Kevin Mayo Pavel Krčmář

根据键列表从dict中获取值

  •  1
  • Kevin Mayo Pavel Krčmář  · 技术社区  · 5 年前

    mapper = {"a": 9, "b": 7}
    A = ["a", "b"]
    

    我想得到:

    result = [9, 7]
    

    我知道有多种方法可以实现这一点,比如:

    result = [mapper[char] for char in A]
    result = list(map(lambda x: mapper[x], A))
    

    第二种方法,我们能用吗 operator

    我发现了一种叫做 operator.getitem() ,我试着用

    result = list(map(operator.getitem(mapper), A))
    

    但这会引起一个例外。

    我知道 list(map(lambda x: operator.getitem(mapper, x), A)) lambda .

    this question

    2 回复  |  直到 5 年前
        1
  •  7
  •   randomir    5 年前

    看来你在找 operator.itemgetter (注意第二个表单,它返回多个项目):

    >>> operator.itemgetter(*A)(mapper)
    (9, 7)
    
        2
  •  1
  •   Tomerikoo Glorified    5 年前

    完整性:

    operator.getitem() ,我试着用 result = list(map(operator.getitem(mapper), A))

    mapper 其中一个元素 A 每次都作为两个独立的参数-因此您不能实际提前调用函数,而是需要“绑定” 制图员 调用的参数。

    为此,我们使用 functools.partial :

    import functools, operator
    
    list(map(functools.partial(operator.getitem, mapper), A))
    

    ( operator.itemgetter 容器 变化-特别是按某个键对嵌套容器进行排序。)