[英]Python: Print non empty lists when multiple lists are present
假设我有 10 个名为 aj 的列表:
我可以检查哪个列表是空的
如果 a.empty:
做一点事
但是我可以通过什么方式只打印非空列表:
对于 aj 中的所有列表:打印(非空列表)
尝试列表推导:
>>> list_of_lists = [[], [1], [], [2,3],[]]
>>> list_of_lists
[[], [1], [], [2, 3], []]
>>> [ l for l in list_of_lists if l]
[[1], [2, 3]]
因为和空列表不是真的, if l
评估为假,所以它不会被拒绝。
您是否尝试过检查列表中的任何元素?
for list_i in all_lists:
if list_i:
print(list_i)
假设您将 10 个列表重新组合到列表 L 中,因此 L 现在是 10 个列表的列表,因此此代码示例打印非空列表,这意味着具有多个元素的列表: for l in L: if (len(l)>0): print(l)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.