嵌套For循环到列表理解

时间:2016-02-18 05:30:47

标签: python list python-2.7 dictionary

鉴于OrderedDict d,我想将嵌套的for循环转换为列表解析。 OrderedDict d如下所示:

import collections
import numpy as np

d = collections.OrderedDict(
    [
        (
            60.0, 
            {
                Timestamp('2016-03-24 00:00:00'): np.nan, 
                Timestamp('2016-03-11 00:00:00'): 2.0173333333333336, 
                Timestamp('2016-02-19 00:00:00'): np.nan, 
                Timestamp('2016-02-26 00:00:00'): np.nan, 
                Timestamp('2016-03-04 00:00:00'): np.nan, 
                Timestamp('2016-03-18 00:00:00'): np.nan, 
                Timestamp('2016-04-01 00:00:00'): np.nan
            }
        ), (
            65.0, 
            {
                Timestamp('2016-03-24 00:00:00'): np.nan, 
                Timestamp('2016-03-11 00:00:00'): np.nan, 
                Timestamp('2016-02-19 00:00:00'): np.nan, 
                Timestamp('2016-02-26 00:00:00'): np.nan, 
                Timestamp('2016-03-04 00:00:00'): 1.8621538461538463, 
                Timestamp('2016-03-18 00:00:00'): np.nan, 
                Timestamp('2016-04-01 00:00:00'): np.nan
            }
        )
    ]
)

您会注意到无序 dicts为值。我的目标是通过时间戳来命令“内部”序列,返回“内部”字典的值。最后,我需要将“内部”dicts的关键字与值结合起来。结果应如下所示:

[
    [60.0, nan, nan, nan 2.0173333333333336, nan, nan, nan],
    [65.0, nan, nan, 1.8621538461538463, nan, nan, nan, nan]
]

以下代码很好地打印出来,我想避免附加到列表中:

for k,v in d.iteritems():
    od = collections.OrderedDict(sorted(v.items()))
    for k_, v_ in od.iteritems():
        print k, k_, v_

我也尝试了以下内容,但它没有按键排序:

for row in [[k] + sorted(v.values()) for k, v in d.iteritems()]:
    print row

因此,希望将此转换为列表理解。

1 个答案:

答案 0 :(得分:1)

[[k] + [v_[1] for v_ in sorted(v.items())] for k,v in d.iteritems()]