繁体   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