简体   繁体   中英

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. So, a nested for loop instead another for loop can be added as a list comprehension as under:

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. 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.

Conditionals/decision making are important because they allow list comprehensions to filter out unwanted values, which would normally require a call to 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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