简体   繁体   English

使用 if() 条件替换的列表理解

[英]List comprehension with if() condition replacement

How to replace if() statements for 2 variables of list comprehension to one complex if comprehension with if() statement.如何用 if() 语句将列表推导的 2 个变量的 if() 语句替换为一个复杂的 if 推导。

Replace this part:替换这部分:

if dictit["any"]:
    listit = [
        dictit["all"] + [x]
        for x in dictit["any"]
    ]
else:
    listit = [dictit["all"]]

In example:例如:

first = {
    "all": []
    , "any": []
}

second = {
    "all": ["1", "2"]
    , "any": ["Student", "Master"]
}

third = {
    "all": []
    , "any": ["Student", "Master"]
}

forth = {
    "all": ["1", "2"]
    , "any": []
}

all_vars = [
    first
    , second
    , third
    , forth
]

for dictit in all_vars:
    if dictit["any"]:
        listit = [
            dictit["all"] + [x]
            for x in dictit["any"]
        ]
    else:
        listit = [dictit["all"]]

    print(listit)

Result:结果:

[[]]
[['1', '2', 'Student'], ['1', '2', 'Master']]
[['Student'], ['Master']]
[['1', '2']]

Like this, but it is not working:像这样,但它不起作用:

    listit = [
        dictit["all"] + [x]
        if dictit["any"] else dictit["all"]
        for x in dictit["any"]
    ]

Please, share your code.请分享您的代码。 Thank you for your time and support.感谢您的时间和支持。

It seems like this would be a good use for itertools.product .似乎这对itertools.product很有用。 Unfortunately, the pre- and post-processing you need make this, well, not the most readable.不幸的是,您需要的预处理和后处理使这不是最易读的。

for dictit in all_vars:
    all_things = dictit["all"]
    any_things = dictit["any"]
    print([list(chain(*t)) for t in product([all_things], [[v] for v in any_things] or [[]])])
[[x['all'], x['any']] if x['any'] else [x['all']] for x in all_vars]

output: output:

[[[]],
 [['1', '2'], ['Student', 'Master']],
 [[], ['Student', 'Master']],
 [['1', '2']]]

I'd do this:我会这样做:

listit = [
    dictit["all"] + [x]
    for x in dictit["any"]
] or [dictit["all"]]

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

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