我有一个字典数组,我想获取一个特定的属性,并基于这些属性创建一个新的字典列表。
我正在尝试使用列表推导来解析每一行,而不是使用传统的循环。可以做到吗?
IAsyncResult
我遇到错误from datetime import datetime
from dateutil.parser import parse
def _format_string_to_timestamp(dt, output):
if dt is None or type(dt) == float:
return ""
origin_dt = parse(dt)
return origin_dt.strftime(output)
def extract_tickets_tags_history(audit):
tag_history = []
sync = "1234"
tags = [d for d in audit['events'] if d.get('field_name', '') == 'tags']
if len(tags) > 0:
return [
{
'tag': tag,
'updated': _format_string_to_timestamp(audit['created_at'], "%Y-%m-%d %H:%M:%S"),
'ticket_id': audit['ticket_id'],
'tagged': False,
'user_id': audit['author_id'],
'sync': sync
}
for tag in tags[-1]['value']]
return None
audit = {
'ticket_id': 123,
'author_id': 654,
'created_at': '2019-04-07T01:09:40Z',
'events': [
{
'field_name': 'tags',
'value': ['taga', 'tagb']
}
]
}
example = [
{
'id': 123,
'data': [audit]
}
]
result = [extract_tickets_tags_history(data) for data in x['data'] for x in example]
...
结果应该类似于NameError: name 'x' is not defined
答案 0 :(得分:2)
您在列表理解中交换了两个for循环
result = [extract_tickets_tags_history(data) for x in example for data in x['data'] ]
等效于
result = []
for x in example:
for data in x['data']:
result.append(extract_tickets_tags_history(data))