简体   繁体   English

如何在Python中将条件循环与for循环结合?

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

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. 我认为可以在Python中以最小的工作量组合if语句和for循环。 Given: 鉴于:

sublists = [number1, number2, number3]

for sublist in sublists:
    if sublist:
        print(sublist)

I thought I could condense the for loop to: 我以为可以将for循环压缩为:

for sublist in sublists if sublist:

but this results in invalid syntax. 但这会导致语法无效。 I'm not too particular on this example, I just want a method of one lining simple if statements with loops. 我在这个例子中不是太特别,我只想要一种简单的if语句循环的方法。

if you want to filter out all the empty sub list from your original sub lists, you will have to do something like below. 如果要从原始子列表中筛选出所有空子列表,则必须执行以下操作。 this will give you all the non empty sub list. 这将为您提供所有非空的子列表。

print([sublist for sublist in sublists if sublist])

*edited for syntax *针对语法进行了编辑

Immediately solved this in the interpreter right after I posted. 我发布后立即在口译员中解决了这个问题。

for x in ( x for x in sublists if x ):

Not as clean as I'd like, the nested if statement is more readable in my opinion. 我认为嵌套的if语句不是我想要的那么干净。 I'm open to other suggestions if there is a cleaner way. 如果有更清洁的方法,我愿意接受其他建议。

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. 我认为您无法将语法简化为python中的单行代码,但是确实必须键入所有循环和if语句的链接行。

An exception to this are list comprehensions ( see here at 5.1.3). 列表理解是一个例外( 请参阅此处的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]

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

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