0

Although I've come across posts that seem to answer this, nothing I've tried from them have worked.

What I want to do is to turn a list like this:

["this is an\nexample" , "sentence\n\x0c"]

to this:

["this", "is", "an", "example", "sentence"]

I'm sure I'm massively overcomplicating this, and usually searching through forums for similar problems works, but for some reason nothing I've come across has been the solution.

Jarvis
  • 8,494
  • 3
  • 27
  • 58
EzekielGMG
  • 21
  • 1

3 Answers3

1

You can try this code. Completely built-in itertools, there are a lot of other functions there that might be useful to you.

from itertools import chain

s = ["this is an\nexample" , "sentence\n\x0c"]


s = [i.split() for i in s]

print(list(chain(*s)))

To make it even shorter like this. But I think the first one is better cause it's more eyes friendly.

from itertools import chain

s = ["this is an\nexample" , "sentence\n\x0c"]
print(list(chain(*[i.split() for i in s])))

Output:

['this', 'is', 'an', 'example', 'sentence']
Ice Bear
  • 2,676
  • 1
  • 8
  • 24
1

Simply do this (map returns you iterator which you directly sum with empty list to return the desired output in one go):

a = ["this is an\nexample" , "sentence\n\x0c"]
a = sum(map(str.split, a), [])

gives

['this', 'is', 'an', 'example', 'sentence']
Jarvis
  • 8,494
  • 3
  • 27
  • 58
  • How do you also apply ```.lower()``` cuz' I get an ```AttributeError: 'method_descriptor' object has no attribute 'lower'``` – Newbielp Oct 02 '21 at 10:33
1

It should be as simple as using a string's split method.

l = ["this is an\nexample" , "sentence\n\x0c"]
l2 = []

for i in l:
    l2 += (i.split())