If anything else is nested for loops using python list understanding

综合编程 2017-12-31

Can anyone help me figure the list comprehension way of producing following output -

Let given list be -

results = [
    {"id":  1, "name":  "input"},
    {"name": "status", "desc": "Status"},
    {"name": "entity", "fields": [
        {"id": 101, "name": "value"},
        {"id": 102, "name": "address"}]

And I am looking for output in the form of list. The code to get the output is:

output = []
for eachDict in results:
    if "fields" in eachDict:
        for field in eachDict["fields"]:

Thus the output using above code is -

['input', 'status', 'entity.value', 'entity.address']

Is it possible to get similar output using if else nested for loops in list Comprehension?

I am having trouble trying to get access to that inner for loop in if condition of list Comprehension

My attempt -

output = [eachDict["name"]+"."+field["name"] for field in eachDict["fields"] if "fields" in eachDict else eachDict["name"] for eachDict in results]

One way to transform your code into workable code would be to make the inner loop produce lists, and then flatten the result afterward.

sum(([d['name'] + '.' + f['name'] for f in d['fields']]
    if d.get('fields') else [d['name']] for d in results), [])
Hello, buddy!

责编内容by:Hello, buddy! (源链)。感谢您的支持!


python面向对象基础 面向对象基础 编程范式 所谓的面向对象编程,指的就是一种编程范式,那么什么是编程范式呢?就是 按照某种语法风格加上数据结构加上算法来编写程序 。 数据结构:列表...
Time.sleep & mdash; Covers... In Python for the *nix, does time.sleep() block the thread or the process? It blocks the...
Python学习笔记十七(MySQL、SQL) 数据库 数据(data)是事实或观察的结果,是对客观事物的逻辑归纳,是用于表示客观事物的未经加工的的原始素材。数据可以是连续的值,比如声音、图像,称为模拟数据。也可以是离散的,如符号、文字,...
Hitchhiker’s guide to the Python imports January 13, 2018 Disclaimer: If you write Python on a daily basis you will find nothing new in th...
Python 源码剖析 – dict 本文所用代码取自 CPython 3.6.3 commit sha 2c5fed86e0cbba5a4e34792b0083128ce659909d 和 dict 相关的源码大致位于三个文件 ...