簡體   English   中英

如何根據 python 中的條件刪除列表列表中的項目?

[英]How do you delete an item in a lists of lists based on a condition in python?

例如

list = [[1,2,3], [4,5,6,3], [3,7,8,9,10,11,12]]

我想刪除所有出現的數字 3。新列表應該是:

[[1, 2], [4, 5, 6], [7, 8, 9, 10, 11, 12]]

這將對您有所幫助。 用戶remove() function 從列表中刪除特定元素

注意: remove() function 不會返回任何東西

list1 = [[1,2,3], [4,5,6,3], [3,7,8,9,10,11,12]]
for l in list1:
  l.remove(3)
print(list1)

Output:

[[1, 2], [4, 5, 6], [7, 8, 9, 10, 11, 12]]

Python 具有 go 的功能,通過一個帶有一個襯里的列表: [each_value for each_value in list]

您可以在條件下使用它: [each_value for each_value in list if each_value is True]

在您的情況下,您可以執行兩次以訪問子列表並排除值3

my_list = [[1,2,3], [4,5,6,3], [3,7,8,9,10,11,12]]
result = [[item for item in sec_list if item != 3] for sec_list in my_list]

->

[[1, 2], [4, 5, 6], [7, 8, 9, 10, 11, 12]]

編輯

對於參差不齊、更復雜的列表:

def delete_threes(l):
    nl = []
    for s in l:
        if isinstance(s, list):
            nl.append(delete_threes(s))
        elif s != 3:
            nl.append(s)
    return nl

上面是一個遞歸的 function,它能夠從形狀參差不齊的列表中刪除3的實例。

首先,我們遍歷列表並檢查元素是子列表還是其他類型。 如果它是一個列表,我們也需要從該列表中遞歸刪除3 這就是nl.append(delete_threes(s))的來源。 這實際上將子列表再次傳遞到 function 中,然后將刪除了3的結果列表附加到新列表nl中。

原來的

您可以使用列表推導在一行中執行此操作:

l = [[1,2,3], [4,5,6,3], [3,7,8,9,10,11,12]]

filtered_l = [[i for i in sub if i != 3] for sub in l]

Output:

[[1, 2], [4, 5, 6], [7, 8, 9, 10, 11, 12]]

如果你不想要一個單線,你可以 go 這個相當丑陋for-loop

filtered_l = []
for sub in l:
    filtered_sub = []
    for i in sub:
        if i != 3:
            filtered_sub.append(i)
    filtered_l.append(filtered_sub)

另一個注意事項:在您的問題中,您定義了名為list的變量。 不鼓勵將您的變量/類/函數命名為與內置函數相同的名稱,因為在追蹤這樣做導致的錯誤后,這可能會導致代碼不可讀和許多令人頭疼的問題。 Go 用於更簡單的東西,比如nums_list或只是l

暫無
暫無

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

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