resolved Split list into parallel lists using python

Viewed 113

I would like to create a parallel list from my original list and then use sort_together

original = ['4,d', '3,b']

parallel list should create 2 lists like this:

lis1 = ['4', '3'] 
list2 = ['d', 'b']

I've tried using split but was only able to obtain a single list :(

[i.split(",", 1) for i in original]
5 Answers

You can use the zip(*...) trick together with .split:

list1, list2 = zip(*(x.split(",") for x in original))

Now this actually gives you two tuples instead of lists but that should be easy to fix if you really need lists.

You can use map and zip:

lis1, list2 = zip(*map(lambda x:x.split(","), original))
  • map will apply the function, passed as first argument (in this case, it simply splits strings on the comma separator) to every element of the iterable (list in this case) passed as second argument. After this, you'll have a map object which contains ['4', 'd'] and ['3', 'b']
  • the zip operator takes two (or more) lists and puts them side by side (like a physical zip would do), creating a lists for elements next to each other. For example, list(zip([1,2,3],[4,5,6])) is [[1.4],[2,5],[3.6]].
  • The unpacking * is necessary given that you want to pass the two sublists in the returned map object.
ini_list = [[4,'d'], [3,'b']]
print ("initial list", str(ini_list))
res1, res2 = map(list, zip(*ini_list))
print("final lists", res1, "\n", res2)

you can use this code for sort and get two list

list1 , list2 = list(sorted(t) for t in (zip(*(item.split(',') for item in orignal))))

for i in range(2):
    s[i] = sorted([oi.split(',')[i] for oi in o])
Related