Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...