Reputation: 83
I have one string list that contains numbers seperated by a comma. I want to create two lists of integers from it. That is:
l=["23,2","11,2","12,7"]
What I want to do is:
l1=[23,11,12]
l2=[2,2,7]
I will appreciate any help.
Upvotes: 2
Views: 4936
Reputation: 211
Ajax1234's way is very pythonic and undoubtedly the best. But maybe this is a bit simpler to understand if new to the language. It uses splicing:
from itertools import chain
l=["23,2","11,2","12,7"]
l = [x.split(',') for x in l] #Split list elements by comma.
l = list(chain.from_iterable(l)) #Get rid of tuples.
list1 = l[::2] #Take every even indexed element, including 0.
list2 = l[1::2] #Takes every odd indexed element.
Output:
[23, 11, 12]
[2, 2, 7]
Here is a link to someone who explains it better.
Upvotes: 1
Reputation: 8078
Can you use zip()
to rip it apart based on splitting each sting by the comma ,
and map
each substring to an int`.
l = ["23,2","11,2","12,7"]
l1, l2 = zip(*[map(int, x.split(',')) for x in l])
# l1 = (23, 11, 12)
# l2 = (2, 2, 7)
Upvotes: 1
Reputation: 71451
You can use zip
:
l=["23,2","11,2","12,7"]
l1, l2 = [list(d) for d in zip(*[[int(i) for i in c.split(',')] for c in l])]
Output:
[23, 11, 12]
[2, 2, 7]
Upvotes: 2