2014-04-25 90 views
1

我有內部列表的字典是這樣的:字典裏面Python列表理解

a = [{'valid': True, 'power': None, 'altitude': 0.0, 'time': datetime.datetime(2014, 4, 7, 16, 5, 55), 'longitude': 47.938, 'course': 0.0, 'address': None, 'latitude': 29.3309, 'speed': 0.0, u'id': 3L, 'device_id': 1L}] 

我只想與time鍵播放,把一切一樣。例如:

[i+timedelta(5) for i in a] 

這工作,但恢復時間列表如下:[.........]這是可以理解的。但我想要的是:

更改時間的原始列表本身的價值,如:

a = [{'valid': True, 'power': None, 'altitude': 0.0, 'time': NEW VALUE, 'longitude': 47.938, 'course': 0.0, 'address': None, 'latitude': 29.3309, 'speed': 0.0, u'id': 3L, 'device_id': 1L}] 

如何做到這一點?

回答

2

使用簡單的for-loop。列表解析用於創建新列表,不要將它們用於副作用。

it = iter(dct['time'] for dct in a) 
tot = sum(it, next(it)) 

for dct in a: 
    dct['time'] = tot 

總結的日期將(在Python 3 functools.reduce)使用reduce()另一種方式:

>>> dates = [dct['time'] for dct in a] 
>>> reduce(datetime.datetime.__add__, dates) 
datetime.datetime(2014, 4, 7, 16, 5, 55) 
+0

該死的男人,爲什麼我沒有想到。謝謝 – pynovice

+0

但如何獲得個人的時間價值和添加。 – pynovice

+0

@ user2032220我不明白你個人的時間價值是什麼意思。一旦你有了答案,請不要刪除這個問題,我幾乎已經向主持人彙報了這一點。 –

0

確保返回的元素,它是在這種情況下字典。否則,您的字典可能會更新(如果寫入正確),但不會作爲結果列表的元素重新出現:

def update(item_dict): 
    item_dict['time'] = item_dict['time'] + timedelta(5) 
    return item_dict 

[update(item_dict) for item_dict in a]