Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split strings in an array into two new arrays [duplicate]

I would like to be able to make an array like list1 = ['a/b','c/d','e/f'] into list2= ['a','c','e'] and list3 = ['b','d','f'].

like image 947
Conasty Avatar asked Jan 30 '26 10:01

Conasty


2 Answers

I would do it this way:

list1 = ['a/b','c/d','e/f']

list2, list3 = map(list, zip(*(x.split('/') for x in list1)))
print(list2, list3)
# ['a', 'c', 'e'] ['b', 'd', 'f']

What you do is to create a generator that yields a tuple consisting of the strings left and right of the / char, respectively. Then use zip() to unfold these into the tuples consisting of the first and second elements, respectively. Finally, map() is used to convert the tuples returned by zip() into lists.

like image 176
Idea O. Avatar answered Jan 31 '26 22:01

Idea O.


[b[0] for b in [a.split('/') for a in list1]]
['a', 'c', 'e']

[b[1] for b in [a.split('/') for a in list1]]
['b', 'd', 'f']
like image 41
pygri Avatar answered Jan 31 '26 22:01

pygri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!