代码之家  ›  专栏  ›  技术社区  ›  wheaties

分配给听写者

  •  2
  • wheaties  · 技术社区  · 16 年前

    如果以前有人问过,请原谅我。我不知道如何寻找它。

    我很熟悉下面这个成语:

    def foo():
        return [1,2,3]
    
    [a,b,c] = foo()
    (d,e,f) = foo()
    

    其中,左侧包含的值将根据右侧函数返回的值进行分配。

    def bar():
        return {'a':1,'b':2,'c':3}
    
    (one, two, three) = bar()
    [four, five, six] = bar()
    

    其中,从右侧返回的钥匙将分配给左侧的容器。

    但是,我很好奇,在Python2.6或更早版本中,是否有一种方法可以执行以下操作:

    {letterA:one, letterB:two, letterC:three} = bar()
    

    它的工作方式是否与序列到序列的工作方式相同?若否,原因为何?天真地尝试按照我写的那样做会失败。

    3 回复  |  直到 16 年前
        1
  •  4
  •   Mark Tolonen    16 年前

    字典项没有顺序,因此,在执行此操作时:

    >>> def bar():
    ...     return dict(a=1,b=2,c=3)
    >>> bar()
    {'a': 1, 'c': 3, 'b': 2}
    >>> (lettera,one),(letterb,two),(letterc,three) = bar().items()
    >>> lettera,one,letterb,two,letterc,three
    ('a', 1, 'c', 3, 'b', 2)
    

    您可以看到,您不一定能够预测变量将如何分配。你可以用 collections.OrderedDict 在Python3中,可以控制此。

        2
  •  1
  •   PaulMcG    16 年前

    mydict = {}
    mydict['existing_key'] = 100
    
    def bar_that_says_dict():
        return { 'new_key': 101 }
    
    mydict.update(bar_that_says_dict())
    
    print mydict
    

        3
  •  -1
  •   mikerobi    16 年前

    不,如果您不能更改bar函数,您可以很容易地从输出创建dict。

    bar dict .

    dict(zip(['one', 'two', 'three'], bar()))