簡體   English   中英

Python-從字典中刪除字典中的空列表

[英]Python-Remove empty list from dictionary from a dictionary

我有一個字典,其中包含另一個包含列表的字典。 我知道這是一場噩夢,但為了對其進行正確分類,我使用了它。

L = {}
for s in range(N):
    L[s] = {}
    for a in A[s]:
        L[s][a] = []
        for i in x:
            if (whatever condition for i):
                L[s][a].append(i)

因此,我的問題是此代碼為每個s的每個a創建一個列表。 然后,如果滿足特定條件,則此列表將充滿元素。 但是,如果未滿足此條件,則列表將為空。 這個事實,即空列表,在我需要刪除該列表之前,在以下計算中給我帶來了嚴重的問題。

總結起來,我需要從以下方面獲取它:

編輯:

0: {0.0: [0.10000000000000001, 0.30000000000000004], 0.10000000000000001: []}, 1:...

至:

0: {0.0: [0.10000000000000001, 0.30000000000000004], 0.10000000000000001:}, 1:....

我有辦法嗎? 我嘗試了.remove()del ,但是我沒有工作。

您可以使用遞歸刪除值為空列表的鍵值對:

s = {0: {0.0: [0.10000000000000001, 0.30000000000000004], 0.10000000000000001: []}}
def new_s(s):
   return {a:(b if not isinstance(b, dict) else new_s(b)) for a, b in s.items() if b}

輸出:

{0: {0.0: [0.1, 0.30000000000000004]}}

僅添加首先包含內容的列表的鍵:

L = {}
for s in range(N):
    L[s] = {}
    for a in A[s]:
        for i in x:
            if (whatever condition for i):
                L[s].setdefault(a, []).append(i)  # new list only if there is content

無需刪除它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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