1

I'm trying to do a simple array & string transformation with Python yet I'm stuck. I have this array :

data = ['one, two, three',  'apple, pineapple',  'frog, rabbit, dog, cat, horse'] 

And I would like to arrive to this result :

new_data = ['one', 'two', 'three', 'apple', 'pineapple', 'frog', 'rabbit', 'dog', 'cat', 'horse']

This is what I'm doing but whenever I use

data_to_string = ''.join(data) 
new_data = re.findall(r"[\w']+", data_to_string)

it gives me this :

['one', 'two', 'threeapple', 'pineapplefrog', 'rabbit', 'dog', 'cat', 'horse']

As you can see "threeapple" and "pineapplefrog" aren't separated, how can I avoid this issue ?

0

3 Answers 3

2

Look into list comprehensions, they're great.

Here's your answer:

[word for string in data for word in string.split(", ")]
Sign up to request clarification or add additional context in comments.

1 Comment

I'll check for list comprehensions then :)
2

How about some simple list comprehension and string methods? re is overkill for this.

>>> data = ['one, two, three',  'apple, pineapple',  'frog, rabbit, dog, cat, horse']
>>> [word.strip() for string in data for word in string.split(',')]
['one', 'two', 'three', 'apple', 'pineapple', 'frog', 'rabbit', 'dog', 'cat', 'horse']

Comments

1

use join and split

','.join(data).split(',')

results in

['one',
 ' two',
 ' three',
 'apple',
 ' pineapple',
 'frog',
 ' rabbit',
 ' dog',
 ' cat',
 ' horse']

1 Comment

Other answers are correct as well. but if you have large array like data*10, then you get performance benefits join and split commands. % timeit ','.join(data*10).split(',') 100000 loops, best of 3: 10.3 µs per loop %timeit [word.strip() for string in data*10 for word in string.split(',')] 10000 loops, best of 3: 42.4 µs per loop. not a big deal, but thought to share.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.