Reputation: 522
Suppose I have a list
['x1_0','x2_1','x3_0']
How can I split the above list into two lists such that the first list contains
['x1','x2','x3']
and the second list [0,1,0]
?
i.e.
('x1_0')
/ \
/ \
/ \
1st list 2nd list
'x1' 0
Feel free to use as many tools as possible. This could obviously done in a single for loop ,which I am aware of. Is there a better way to do this ?. Something which uses list comprehension ? Als
Upvotes: 2
Views: 141
Reputation: 107287
You can use zip
and a list comprehension :
>>> zip(*[i.split('_') for i in l])
[('x1', 'x2', 'x3'), ('0', '1', '0')]
And if you want to convert the second tuple's elements to int you can use the following nested list comprehension :
>>> [[int(i) if i.isdigit() else i for i in tup] for tup in zip(*[i.split('_') for i in l])]
[['x1', 'x2', 'x3'], [0, 1, 0]]
The preceding way is the proper way to do this task but as you say in comment as a smaller solution you can use map
:
>>> l=[l[0],map(int,l[1])]
>>> l
[('x1', 'x2', 'x3'), [0, 1, 0]]
Upvotes: 6
Reputation: 67968
k=["x1_0","x2_1","x3_0"]
k1=[x.split("_")[0] for x in k]
k2=[int(x.split("_")[1]) for x in k]
You can do this simply this way.
Upvotes: 1