简体   繁体   English

在这种情况下我们可以形成一个Python列表理解吗?

[英]Can we form a Python List Comprehension in this case?

I recently learnt that we can include multiple loops in a python list comprehension, just like the sequence of the for loop in traditional manner.我最近了解到,我们可以在 python 列表解析中包含多个循环,就像传统方式中的 for 循环序列一样。 So, a nested for loop instead another for loop can be added as a list comprehension as under:因此,可以添加一个嵌套的 for 循环而不是另一个 for 循环作为列表推导,如下所示:

result_list = [sub for part in parts for sub in part if sub > 10]

However, I got confused in one scenario where the number of 'sub' is too long, while the condition of if can be completely ignored on the rest if even one sub breaks the rule.但是,我在一种情况下感到困惑,即“子”的数量太长,而在 rest 上,即使有一个子违反了规则,也可以完全忽略 if 的条件。 So instead of checking all the sub in the part, I break the loop when the condition breaks and move on to next parts.因此,我没有检查零件中的所有子,而是在条件中断时打破循环并继续下一个零件。

I am sharing a scenario from the code I am working on.我正在从我正在处理的代码中分享一个场景。

for part in parts:
    for sub in part:
        if sub not in a_list:
            var = False
            break
    if var == True:
        b_list.append(part)

The above code works.上面的代码有效。 Just out of curiosity to learn the language, can we do this in list comprehension format?只是出于对学习语言的好奇,我们可以用列表理解格式来做吗?

I am at this, so sorry if I miss something.我在这,如果我错过了什么,很抱歉。

The list comprehension syntax adds support for optional decision making/conditionals.列表理解语法增加了对可选决策/条件的支持。 The most common way to add conditional logic to a list comprehension is to add a conditional to the end of the expression:将条件逻辑添加到列表推导的最常见方法是在表达式末尾添加条件:

like so:像这样:

new_list = [expression for member in iterable (if conditional)]

Here, your conditional statement/if statement comes just before the closing bracket or after the loop if there are more than one loop like i your scenario.在这里,您的条件语句/if 语句就在右括号之前或循环之后,如果有多个循环,就像我的场景一样。

Conditionals/decision making are important because they allow list comprehensions to filter out unwanted values, which would normally require a call to filter():条件/决策很重要,因为它们允许列表推导过滤掉不需要的值,这通常需要调用filter():

Here is the complete list comprehension that you asked for:这是您要求的完整列表理解:

b_list = [part for part in parts if all(sub in a_list for sub in part)]

For more information or help on list comprehensionsgo here有关列表理解的更多信息或帮助,请转到此处

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

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