且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python从列表列表中删除空元素

更新时间:2022-05-27 22:05:03

您的尝试将从列表列表中删除空列表,而不是从子列表中删除空元素。而是将过滤器应用于子列表:

Your attempt will remove empty lists from the list of lists, not empty elements from the sublists. Instead, apply the filter to the sublists:

str_list = [list(filter(None, lst)) for lst in list_of_lists]

filter()的调用已包装与 list()一起使用,以防您稍后在python3中尝试此操作,因为 filter()返回py3中的迭代器。

The call to filter() is wrapped with list() in case you happen to try this in python3 later, as filter() returns an iterator in py3.

请注意,由于您将此标签标记为您可能必须要小心,因为过滤可能会产生长度不同的行,并且列中的项目会出现错误。如果您知道每一行的最后2个项目始终为空,则可以将它们切成薄片:

Note that since you tagged this as csv you might have to be careful as filtering might produce rows with differing lengths and items in wrong columns. If you know that for each row the 2 last items will always be empty, you could slice them out:

str_list = [row[:-2] for row in list_of_lists]