如何在Python中将条件循环与for循环结合? [英] How can I combine a conditional with a for loop in Python?

查看:187
本文介绍了如何在Python中将条件循环与for循环结合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的例子.我认为可以在Python中以最小的工作量组合if语句和for循环.鉴于:

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 = [number1, number2, number3]

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

我认为我可以将for循环压缩为:

I thought I could condense the for loop to:

for sublist in sublists if sublist:

但这会导致语法无效.在这个例子中,我并不是特别讲究,我只想要一种简单的if语句带循环的方法.

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

这篇关于如何在Python中将条件循环与for循环结合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆