【问题标题】:How to convert a dict of lists to a list of tuples of key and value in python?python - 如何将列表的字典转换为python中键和值的元组列表?
【发布时间】:2015-05-02 16:04:59
【问题描述】:

我有一个这样的列表:

y = {'a':[1,2,3], 'b':[4,5], 'c':[6]}

我想将dict转换成一个元组列表,每个元素都是一个元组,包含dict的一个键和值列表中的一个元素:

x = [
    ('a',1),('a',2),('a',3),
    ('b',4),('b',5),
    ('c',6)
    ]

我的代码是这样的:

x = reduce(lambda p,q:p+q, map(lambda (u,v):[(u,t) for t in v], y.iteritems()))

这样的代码似乎很难阅读,所以我想知道是否有任何pythonic方式,或者更准确地说,是列表理解中的一种方式来做这样的事情?

【问题讨论】:

    标签: python list python-2.7 dictionary


    【解决方案1】:

    你可以这样做,

    >>> y = {'a':[1,2,3], 'b':[4,5], 'c':[6]}
    >>> [(i,x) for i in y for x in y[i]]
    [('a', 1), ('a', 2), ('a', 3), ('c', 6), ('b', 4), ('b', 5)]
    

    【讨论】:

      【解决方案2】:

      另一种方法,但不一定更具可读性或pythonic:

      >>> from itertools import izip_longest
      >>> y = {'a':[1,2,3], 'b':[4,5], 'c':[6]}
      >>> [tuple(izip_longest(k, v, fillvalue=k)) for k, v in y.items()]
      [(('a', 1), ('a', 2), ('a', 3)), (('c', 6),), (('b', 4), ('b', 5))]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多