2

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)
Firefly
  • 449
  • 5
  • 20
  • Possible duplicate of [Python: How to remove empty lists from a list?](http://stackoverflow.com/questions/4842956/python-how-to-remove-empty-lists-from-a-list) – Sandeep May 13 '16 at 07:46

2 Answers2

7

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 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]
Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
  • Note to OP: even in Python 3 the `list` call is optional depending on what you need to do. Iterators aren't evil, they just support less things like indexing. – Alex Hall May 13 '16 at 07:49
  • Indeed, was just trying to keep the data closer to the original. Iterators really are handy, if you later have to go over the data just once. – Ilja Everilä May 13 '16 at 07:56
1

You can do with join

output = [' '.join(i).split() for i in list_of_list]

Ouput

[['A001', 'atendimento', 'sust', 'concession\xc3\xa1rio', 'adv', 'bom', 'adj'],['A001', 'falar', 'verb', 'ter', 'verb', 'nada', 'pron', 'carro', 'sust'],['A001','n\xc3\xa3o','adv','perguntar','verb','problema','sust','carro','sust'],['A001','n\xc3\xa3o','adv','oferecer','verb','ligar','verb','compra','sust'],['A001','n\xc3\xa3o','adv','oferecer','verb','servi\xc3\xa7o','sust','compra','sust']]
Rahul K P
  • 15,740
  • 4
  • 35
  • 52