簡體   English   中英

根據子列表的Len刪除列表的子列表

[英]Removing sublists of Lists based on Len of sublists

我最近開始學習python,我需要你的幫助。 我有一個列表列表,我需要刪除len低於某個數字的列表。

我已經檢查了關於使用列表列表的許多問題和答案,但我沒有找到任何有關這種特定情況的信息,所以我將非常感謝你的幫助。

我的例子:

Records = [[1,2], [3,4], [5,6,7], [8,9,10], [11], [12,13,14,15]]

而且我想要消除len低於3的列表。所以最后

我希望有 :

Records = [[5,6,7], [8,9,10],[12,13,14,15]]

我想我必須做一個循環迭代所有列表並檢查len並消除那些len > 3但我不知道如何編碼。 你能幫我么?

謝謝!

如此天真,這就像是

result = []
for record in Records:         # iterate over each element of the list
    if len(record) >= 3:       # your filter requirement
        result.append(record)  # adding it to the results we want
print(result)

與其他答案一樣,您可以使用具有結構的列表推導來壓縮代碼

[element for element in iterable if filter(element)]

在你的情況下:

[record for record in Records if len(record) >= 3]
result = [record for record in records if len(record) >= 3]

就這么簡單:

Records = [[1,2], [3,4], [5,6,7], [8,9,10], [11], [12,13,14,15]]

[i for i in Records if len(i)>=3]

輸出:

[[5, 6, 7], [8, 9, 10], [12, 13, 14, 15]]

暫無
暫無

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

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