gpt4 book ai didi

Python 字典内的列表理解

转载 作者:行者123 更新时间:2023-12-01 05:15:40 25 4
gpt4 key购买 nike

我的列表中有一本字典,如下所示:

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}]

如何做到这一点?

最佳答案

使用简单的 for 循环。列表推导式用于创建新列表,不要将它们用于副作用。

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

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

对日期求和的另一种方法是使用 reduce()(Python 3 中的functools.reduce):

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

关于Python 字典内的列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23292620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com