How can I combine a conditional with a for loop in Python?

后端 未结 3 968
囚心锁ツ
囚心锁ツ 2021-01-22 01:08

I have a simple example I\'ve drawn up. I thought it was possible to combine if statements and for loops with minimal effort in Python. Given:

sublists = [numb         


        
3条回答
  •  暖寄归人
    2021-01-22 01:32

    I think you can't simplify the syntax to a one-liner in python, but indeed have to type out all the lines chaining for loops and if statements.

    An exception to this are list comprehensions (see here at 5.1.3). They can be used to produce new lists from lists. An example:

    test_list = ["Blue Candy", "Apple", "Red Candy", "Orange", "Pear", "Yellow Candy"]
    candy_list = [x for x in test_list if "Candy" in x]
    

提交回复
热议问题