Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lists and their splitting

Tags:

python

list

For example, I have such code

a = ["a;b", "c;d",...,"y;z"]

I want to split every list element into to items of the same list. So i wanna get something like this:

["a", "b", "c", "d", ...., "y", "z"]

How can I do such thing? Thanks for your answers.

like image 582
alexvassel Avatar asked Dec 02 '22 03:12

alexvassel


2 Answers

Using only string operations seem to be simplest (this is subjective, of course) and fastest (by a huge margin, compared to other solutions posted so far).

>>> a = ["a;b", "c;d", "y;z"]
>>> ";".join(a).split(";")
['a', 'b', 'c', 'd', 'y', 'z']

Proof / benchmarks

Sorted in ascending order of elapsed time:

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' '";".join(a).split(";")'
10000 loops, best of 3: 48.2 usec per loop

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' '[single for pair in a for single in pair.split(";")]'
1000 loops, best of 3: 347 usec per loop

python -mtimeit -s'from itertools import chain; a=["a;b","x;y","p;q"]*99' 'list(chain(*(s.split(";") for s in a)))'
1000 loops, best of 3: 350 usec per loop

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' 'sum([x.split(";") for x in a],[])'
1000 loops, best of 3: 1.13 msec per loop

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' 'sum(map(lambda x: x.split(";"), a), [])'
1000 loops, best of 3: 1.22 msec per loop

python -mtimeit -s'a=["a;b","x;y","p;q"]*99' 'reduce(lambda x,y:x+y, [pair.split(";") for pair in a])'
1000 loops, best of 3: 1.24 msec per loop
like image 128
Shawn Chin Avatar answered Dec 04 '22 09:12

Shawn Chin


You can use itertools.chain:

>>> a = ["a;b", "c;d","y;z"]
>>> list(itertools.chain(*(s.split(';') for s in a)))
['a', 'b', 'c', 'd', 'y', 'z']
like image 36
Felix Kling Avatar answered Dec 04 '22 09:12

Felix Kling