简体   繁体   English

如果使用python列表理解嵌套嵌套循环

[英]if else nested for loops using python list comprehension

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"]:
            output.append(eachDict["name"]+"."+field["name"])
    else:
        output.append(eachDict["name"])

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? 如果在列表理解中嵌套了for循环,是否有可能获得类似的输出?

I am having trouble trying to get access to that inner for loop in if condition of list Comprehension 如果列表理解的条件,我在尝试访问该内部for循环时遇到麻烦

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), [])

A list comprehension has a fixed number of (nested) loops. 列表推导具有固定数量的(嵌套)循环。 So must have two loops here, one over the top-level dictionaries, and one over the fields . 因此,这里必须有两个循环,一个在顶级字典上,另一个在fields The trick is to produce one iteration in the nested loop if there are no fields: 诀窍是如果没有字段,则在嵌套循环中产生一个迭代:

[d['name'] + fieldname 
 for d in results
 for fieldname in (
    ('.' + sub['name'] for sub in d['fields']) if 'fields' in d else
    ('',))
]

The for fieldname loop loops either over the names of the fields sub-directories (with '.' prefixed), or over a tuple with just a single empty string in it. for fieldname回路循环要么在名称fields子目录(用'.'前缀), 在与它只是一个空字符串的元组。

Note that this isn't actually all that readable. 请注意,这实际上并不是所有可读性。 I'd delegate producing the fieldname loop to a helper generator function to improve that: 我将产生fieldname循环委托给一个辅助生成器函数来改善这一点:

def fieldnames(d):
    if 'fields' in d:
        for sub in d['fields']:
            yield '.' + sub['name']
    else:
        yield ''

[d['name'] + fieldname for d in results for fieldname in fieldnames(d)]

Demo: 演示:

>>> def fieldnames(d):
...     if 'fields' in d:
...         for sub in d['fields']:
...             yield '.' + sub['name']
...     else:
...         yield ''
...
>>> [d['name'] + fieldname for d in results for fieldname in fieldnames(d)]
['input', 'status', 'entity.value', 'entity.address']

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

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