How to split strings in an array into two new arrays

Viewed 1308

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'].

4 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.

[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']

In one line :

list1 = ['a/b','c/d','e/f']
list2, list3 = [x.split('/')[0] for x in list1], [x.split('/')[1] for x in list1]
 l2 = []
 l3 = []
 l1 = ['a/b','c/d','e/f']
 for item in l1:
        item1, item2 = item.split("/")
        l2.append(item1)
        l3.append(item2)
Related