簡體   English   中英

刪除列表中的空嵌套列表

[英]Remove empty nested lists within list

請參閱下面的確切代碼。 基本上,我試圖從csv文件中獲取信息,並創建一個包含所有用戶名(無空格或重復項)的列之一的列表。 我可以獲取所有用戶名的列表,但找不到消除空白的方法。 我已經嘗試過過濾器以及其他方法,但似乎無法正確處理。 我的代碼是:

with open('test.csv') as f:
reader = csv.DictReader(f)
initialExport = []
for row in reader:
    iE = [row['Computer Name'], row['Username']]
    initialExport.append(iE)

for i in initialExport:
    i.pop(0)
finalExport = filter(None, initialExport)
print(finalExport)

而不是將其過濾掉,為什么不只是避免首先添加空白條目:

for row in reader:
    if row['Username']:
        iE = [row['Computer Name'], row['Username']]
        initialExport.append(iE)

當您嘗試過濾initialExport是(單個)列表的列表。 其中一些列表可能包含空字符串。 那不會使他們成為空名單! 因此,無論如何,他們的真實性都是真實的。 您可以通過以下方式過濾掉它們:

finalExport =  [l for l in initialExport if l[0]]

但是,如果只彈出它,為什么還要首先添加“ Computer Name列呢? 如果只對一個元素感興趣,為什么還要創建一個嵌套列表:

finalExport = [row['Username'] for row in reader if row['Username']]

這顯示了從lst刪除空列表,空元組和僅包含空列表的列表的方法。 以下代碼不會刪除:

  • 空嵌套元組(具有一個或多個級別)
  • 具有兩個以上級別的空嵌套列表

授予lst的最后兩個條目。

import collections

lst = [1, 2, "3", "three", [], [1, 2, "3"], [[], []], 4,
       [[1], []], [[], [], []], 5, "6", (1,2), 7, (),
       ((), ()), [[[]]]]

for index, item in enumerate(lst):
    # if it is an empty list [] or tuple ()
    if not item:
        del lst[index]
    # if it is a list containing only empty sublists [[], [], ...]
    elif isinstance(item, collections.MutableSequence):
        if not [i for sublist in item for i in sublist]:
            del lst[index]

print(lst)

輸出:

[1, 2, '3', 'three', [1, 2, '3'], 4, [[1], []], 5, '6', (1, 2), 7, ((), ()), [[[]]]]

在上面的示例中,從第一個元素中刪除了四個元素,即[],[[],[]],[[],[],[]]和()。

purge(list, [elements to purge])將遞歸清除列表和所有子列表中所有element副本,包括通過刪除更深層元素創建的任何元素( [[[], []]]將被完全刪除)。 因為我們要就地修改列表,所以每次刪除元素時,我們都必須在當前深度重新啟動:

def purge(lst, bad):
    restart = True
    while restart:
        restart = False
        for index, ele in enumerate(lst[:]):
            if ele in bad:
                del lst[index]
                restart = True
                break
            elif isinstance(ele, list):
                purge(ele, bad)
                if lst[index] in bad:
                    del lst[index]
                    restart = True
                    break

例子:

>>> lst = [[[[], [[],[]]]]]
>>> purge(lst, [[]])
[]

>>> lst = [1, 2, "3", "three", [], [1, 2, "3"], [[], []], 4,
       [[1], []], [[], [], []], 5, "6", (1,2), 7, [[[]]]]
>>> purge(lst, [[]])
[1, 2, '3', 'three', [1, 2, '3'], 4, [[1]], 5, '6', (1, 2), 7]
>>> purge(lst, ['3'])
[1, 2, 'three', [1, 2], 4, [[1]], 5, '6', (1, 2), 7]

暫無
暫無

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

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