简体   繁体   English

从列表中删除空条目的子列表

[英]Removing sublists of empty entries from a list

I've got a list that looks like this: 我有一个看起来像这样的列表:

some_list = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['', '', '', '']]

I want to remove all empty sublists within the list, so that the product is just 我想删除列表中的所有空子列表,以便产品只是

clean_list = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']]

I've tried the following 我尝试了以下

for x in some_list:
    if x == ['', '', '', '']:
        some_list.remove(x)

and

clean_list = filter(None, list)

and

clean_list = [x for x in list if x]

but I keep getting an output with sublists with empty entries. 但我不断得到带有空条目的子列表的输出。 Thoughts? 有什么想法吗?

Use the any() function to select lists with non-empty values: 使用any()函数 选择具有非空值的列表:

clean_list = [sublist for sublist in some_list if any(sublist)]

any() short-circuits; any()短路; iterating over the values in sublist it'll return True as soon as it finds a true (non-empty) string in that sublist, and only returns False after testing all values, finding them to be empty. 遍历sublist的值后,一旦在该子列表中找到一个真(非空)字符串,它将立即返回True ,并且在测试所有值后发现它们为空,仅返回False

Your x == ['', '', '', ''] loop failed because you were modifying a list while iterating over it. 您的x == ['', '', '', '']循环失败,因为您在迭代列表时正在修改列表。 As the list gets shorter, iteration starts skipping later elements as they have shifted indices, see strange result when removing item from a list for more detail. 随着列表的缩短,迭代将开始跳过后面的元素,因为它们的索引已移动, 从列表中删除项目时会看到奇怪的结果,以获取更多详细信息。

Your filter(None, ..) attempt fails because ['', '', '', ''] is itself not a false value , it is a non-empty list, there are 4 strings in it. 您的filter(None, ..)尝试失败,因为['', '', '', '']本身不是一个假值 ,它是一个非空列表,其中有4个字符串。 It doesn't matter that those strings are empty. 那些字符串为空并不重要。 The same applies to your list comprehension; 这同样适用于您的列表理解; all lists in some_list are non-empty, so all are considered true . some_list中的所有列表都是非空的,因此都被视为true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM