[英]Nested For Loop to List Comprehension
Given an OrderedDict
d
, I'd like to convert a nested for
loop to a list comprehension. 给定
OrderedDict
d
,我想将嵌套的for
循环转换for
列表推导。 The OrderedDict
d
looks like this: 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
}
)
]
)
You'll notice there are unordered dicts as values. 您会注意到有无序的 dict作为值。 My goal is to order the "internal" dicts by timestamp, the return the values of the "internal" dict.
我的目标是按时间戳排序“内部”字典,返回“内部”字典的值。 Finally, I need to combine the key of the "internal" dicts with the values.
最后,我需要将“内部”字典的键与值结合起来。 Result should look like this:
结果应如下所示:
[
[60.0, nan, nan, nan 2.0173333333333336, nan, nan, nan],
[65.0, nan, nan, 1.8621538461538463, nan, nan, nan, nan]
]
The following code prints this out nicely and I want to avoid appending to a list: 以下代码很好地打印了此内容,我想避免附加到列表中:
for k,v in d.iteritems():
od = collections.OrderedDict(sorted(v.items()))
for k_, v_ in od.iteritems():
print k, k_, v_
I've also tried the following but it does not sort by key: 我也尝试了以下方法,但是它不是按键排序的:
for row in [[k] + sorted(v.values()) for k, v in d.iteritems()]:
print row
Therefore, looking to convert this to a list comprehension. 因此,希望将其转换为列表理解。
[[k] + [v_[1] for v_ in sorted(v.items())] for k,v in d.iteritems()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.