3

d is a string list where each item is composed of two parts (connected by a dot). I want to extract the parts before and after the dot for each string item.

Here is how I did it.

d = ['a1.b1', 'a2.b2', 'a3.b3']
b = [c.split('.')[0] for c in d]
a = [c.split('.')[1] for c in d]

But I guess there is some more pythonic way?

1
  • very similar except simpler than mine Commented Nov 11, 2015 at 22:41

1 Answer 1

7

You can use zip() function:

>>> a,b = zip(*[i.split('.') for i in d])
>>> a
('a1', 'a2', 'a3')
>>> b
('b1', 'b2', 'b3')
Sign up to request clarification or add additional context in comments.

6 Comments

You don't need to use a list comp zip(*(i.split('.') for i in d))
@PadraicCunningham I think using list comprehension has more performance than generator expression in terms of execution time. Because by using generator expression python will does an extra jobs again (calling the generator function and using iter and next methods ), ;-) . read my answer here stackoverflow.com/questions/33634130/…
If you have large amounts of data you are potentially creating multiple copies which may cause issue
@PadraicCunningham Yep, in terms of memory use actually a generator expression would performs so much better.
Watch out, though; if d is empty, the assignment will fail due to not enough values to unpack!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.