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.
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']
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
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With