Home > front end >  Remove individual spaces in list
Remove individual spaces in list

Time:03-01

I have this list of lists with words and their respective part of speech tags, which I want to put into a dictionary. The only problem is that among these I also have strings which are just spaces, for example:

['he', 'pron', ' ', 'did', 'aux', ' ', "n't", 'part', ' ', 'mention', 'verb', ' ', 'anything', 'pron', ' ', 'about', 'adp', ' ', 'it', 'pron', ' ', '.', 'punct', '\n']

As you can see, in the example I copied I have the empty spaces in quotes, as between 'pron' and 'did'. How can I get rid of all of these, so I could be left for example only with

['he', 'pron', 'did', 'aux', "n't", 'part', 'mention', 'verb', 'anything', 'pron', 'about', 'adp', 'it', 'pron', '.', 'punct', '\n']

CodePudding user response:

Simplest to do with a list comprehension:

words = [word for word in words if word != ' ']

CodePudding user response:

is this what you are expecting

inputarr = ['he', 'pron', ' ', 'did', 'aux', ' ', "n't", 'part', ' ', 'mention', 'verb', ' ', 'anything', 'pron', ' ', 'about', 'adp', ' ', 'it', 'pron', ' ', '.', 'punct', '\n']
outputarr= []
for i in inputarr:
  if i ==' ':
    pass
  else:
    outputarr.append(i)
print(outputarr)
  • Related