簡體   English   中英

Python:存在多個列表時打印非空列表

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM