I have a list of lists like this:
[['A001', 'atendimento', 'sust', 'concessionário', 'adv', 'bom', 'adj', '', ''],
['A001', 'falar', 'verb', 'ter', 'verb', 'nada', 'pron', 'carro', 'sust', '', ''],
['A001', 'não', 'adv', 'perguntar', 'verb', 'problema', 'sust', 'carro', 'sust', '', ''],
['A001', 'não', 'adv', 'oferecer', 'verb', 'ligar', 'verb', 'compra', 'sust', '', ''],
['A001', 'não', 'adv', 'oferecer', 'verb', 'serviço', 'sust', 'compra', 'sust', '', '']]
And I want to remove empty elements from each list getting a new list of lists without the empty elements:
[['A001', 'atendimento', 'sust', 'concessionário', 'adv', 'bom', 'adj'],
['A001', 'falar', 'verb', 'ter', 'verb', 'nada', 'pron', 'carro', 'sust'],
['A001', 'não', 'adv', 'perguntar', 'verb', 'problema', 'sust', 'carro', 'sust'],
['A001', 'não', 'adv', 'oferecer', 'verb', 'ligar', 'verb', 'compra', 'sust'],
['A001', 'não', 'adv', 'oferecer', 'verb', 'serviço', 'sust', 'compra', 'sust']]
How could I achieve this?
I tried this:
str_list = filter(None, list_of_lists)
解决方案
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]
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.
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]