请问有人可以帮我想出用列表推导式生成下面的输出吗:
给定一个列表:
results = [
{"id": 1, "name": "input"},
{"name": "status", "desc": "Status"},
{"name": "entity", "fields": [
{"id": 101, "name": "value"},
{"id": 102, "name": "address"}]
}
]
我希望您能将输出以列表形式呈现。获取输出的代码如下:
output = []
for eachDict in results:
if "fields" in eachDict:
for field in eachDict["fields"]:
output.append(eachDict["name"]+"."+field["name"])
else:
output.append(eachDict["name"])
因此,使用上述代码的输出为 -
['input', 'status', 'entity.value', 'entity.address']
是否可以使用if else嵌套for循环在列表推导中获得类似的输出?
我正在尝试访问列表推导式中if条件中的内部for循环,但遇到了困难。
我的尝试 -
output = [eachDict["name"]+"."+field["name"] for field in eachDict["fields"] if "fields" in eachDict else eachDict["name"] for eachDict in results]
[item for sublist in [['{0}.{1}'.format(d['name'], f['name']) for f in d['fields']] if 'fields' in d else [d['name']] for d in results] for item in sublist]
。 - Dom Weldon