繁体   English   中英

字典中的Python列表理解

[英]Python list Comprehension inside dictionaries

我在列表中有这样的字典:

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

functools.reduce日期的另一种方法是使用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)

确保返回一个元素,在这种情况下为字典。 否则,您的字典可能会更新(如果书写正确),但不会重新出现在结果列表的元素中:

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

[update(item_dict) for item_dict in a]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM