1

Im trying to loop through a list in python and split words based on characters. I want to return a 1 dimension list as the result.

Example

wordlist = ['border\collie', 'dog\cat', 'horse\hound'] # slash fix

Expected outcome new_list = ['border', 'collie', 'dog', 'cat', 'horse', 'hound']

Everything that Ive tried results in a 2d list.

def split_slash_words(text):
    new_list = []
    new_list.append([i.split("\\") for i in text])
    return new_list

returned a two dimensional array, and I cannot also resplit the new_list (as it is in a list type)

jordiburgos
  • 5,964
  • 4
  • 46
  • 80
user5067291
  • 440
  • 1
  • 6
  • 16

2 Answers2

5
import re
wordlist = ['border/collie', 'dog\cat', 'horse/hound']

out = []
for item in wordlist:
    for element in re.findall('\w+', item):
        out.append(element)

Output:

['border', 'collie', 'dog', 'cat', 'horse', 'hound']
Zaraki Kenpachi
  • 5,510
  • 2
  • 15
  • 38
3

The append method adds a list to the end of new_list. If you use the extend method, each item is added to new_list.