我有一个看起来像
的字典{'2016-05-30':{
'go':((1, 2, 3, 4),),
'stop':((5, 6, 7, 8),)},
'2016-05-31': {
'go':((11, 12, 13, 14),),
'stop':((15, 16, 17, 18),)}}
我有一份州名单:['state1', 'state2', 'state3', 'state4']
我正在尝试获得看起来像(state, date, value)
我可以通过运行一堆for
循环来实现:
some_list=[]
state = ['state1', 'state2', 'state3', 'state4']
data = {'2016-05-30':{
'go':((1, 2, 3, 4),),
'stop':((5, 6, 7, 8),)},
'2016-05-31': {
'go':((11, 12, 13, 14),),
'stop':((15, 16, 17, 18),)}}
for d in data:
for vals in data.values():
for val in vals.get('go'):
if val:
for k,v in zip(state, val):
some_list.append((k, d, v))
这是非常强大的力量,我想知道是否有更聪明的方式/ pythonic方式来做它
编辑:好的,现在使用实际值而不是假值(大多数情况下)。应该更清楚。代码应该能够进行copypasta-ed
答案 0 :(得分:1)
以下是我认为你想要的,使用列表推导,
some_list = [[s, d, v] for d in data for vals in data[d]['go'] for s, v in zip(state, vals)]
# [['state1', '2016-05-31', 11],
# ['state2', '2016-05-31', 12],
# ['state3', '2016-05-31', 13],
# ['state4', '2016-05-31', 14],
# ['state1', '2016-05-30', 1],
# ['state2', '2016-05-30', 2],
# ['state3', '2016-05-30', 3],
# ['state4', '2016-05-30', 4]]
如果字段“去”'并不总是存在,你可以使用
[[s, d, v] for d in data for f in data[d] for vals in data[d][f] for s, v in zip(state, vals) if f == 'go']