[英]Python: Print non empty lists when multiple lists are present
So let's say I have 10 lists named aj:假设我有 10 个名为 aj 的列表:
I can check which list is empty我可以检查哪个列表是空的
if a.empty:
如果 a.empty:
do something
做一点事
But in what way can I print only the non empty lists:但是我可以通过什么方式只打印非空列表:
for all lists in aj: print(non-empty lists)
对于 aj 中的所有列表:打印(非空列表)
try list comprehensions:尝试列表推导:
>>> list_of_lists = [[], [1], [], [2,3],[]]
>>> list_of_lists
[[], [1], [], [2, 3], []]
>>> [ l for l in list_of_lists if l]
[[1], [2, 3]]
because and empty list is not truthy , if l
evaluates to false when the list is empty, so it is not witheld.因为和空列表不是真的,
if l
评估为假,所以它不会被拒绝。
have you tried just check for any element in the list?您是否尝试过检查列表中的任何元素?
for list_i in all_lists:
if list_i:
print(list_i)
let's suppose that you regrouped your 10 lists in a list L so L is now a list of your 10 lists,so this sample of code print the non empty lists which means those who have more than one element: for l in L: if (len(l)>0): print(l)
假设您将 10 个列表重新组合到列表 L 中,因此 L 现在是 10 个列表的列表,因此此代码示例打印非空列表,这意味着具有多个元素的列表:
for l in L: if (len(l)>0): print(l)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.