简体   繁体   English

删除列表中的空嵌套列表

[英]Remove empty nested lists within list

See below for the exact code. 请参阅下面的确切代码。 Basically, I am trying to take information from a csv file and create a list with one of the columns that has all the usernames (with no blanks or duplicates). 基本上,我试图从csv文件中获取信息,并创建一个包含所有用户名(无空格或重复项)的列之一的列表。 I am able to get a list of all the usernames, but I can not find a way to remove the blanks. 我可以获取所有用户名的列表,但找不到消除空白的方法。 I have tried both filter as well as other methods, but can't seem to get it right. 我已经尝试过过滤器以及其他方法,但似乎无法正确处理。 My code is: 我的代码是:

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)

Rather than filtering it out, why not just avoid adding blank entries in the first place: 而不是将其过滤掉,为什么不只是避免首先添加空白条目:

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

initialExport is a list of (singleton) lists when you try to filter them. 当您尝试过滤initialExport是(单个)列表的列表。 Some of these lists might contain the empty string. 其中一些列表可能包含空字符串。 That does not make them empty lists! 那不会使他们成为空名单! So their truthiness is true no matter what. 因此,无论如何,他们的真实性都是真实的。 You could filter them out via: 您可以通过以下方式过滤掉它们:

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

But why add the Computer Name column in the first place if you just pop it? 但是,如果只弹出它,为什么还要首先添加“ Computer Name列呢? And why make a nested list if you are just interested in one element: 如果只对一个元素感兴趣,为什么还要创建一个嵌套列表:

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

This shows a way to remove empty lists, empty tuples and lists containing only empty lists from lst. 这显示了从lst删除空列表,空元组和仅包含空列表的列表的方法。 The code below will not remove: 以下代码不会删除:

  • empty nested tuples (with one or more levels) 空嵌套元组(具有一个或多个级别)
  • empty nested lists with more than two levels 具有两个以上级别的空嵌套列表

Confer the last two entries of 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)

Output: 输出:

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

Four elements are removed from lst in the above example, namely [], [[], []], [[], [], []] and (). 在上面的示例中,从第一个元素中删除了四个元素,即[],[[],[]],[[],[],[]]和()。

purge(list, [elements to purge]) will recursively purge all copies of element from the list and any sublists, including any elements created by removing deeper elements ( [[[], []]] will be entirely removed). purge(list, [elements to purge])将递归清除列表和所有子列表中所有element副本,包括通过删除更深层元素创建的任何元素( [[[], []]]将被完全删除)。 Because we're modifying the list in-place, we have to restart at our current depth every time we remove an 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

Examples: 例子:

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