pythonlistreformat

Python 3.6 - separating the columns in multiple lists into new lists


here is my code that counts the number of times unique numbers appear and looks for numbers that repeat 5 times in list A, then any that repeat 2 times in list A as well, and prints the results of any matches of list A with corresponding value from list B. Also list A and B are always the same size.

a = (['12','12','12','12','12','23','24','24','31','31'])
b = (['1','2','2','2','2','2','5','5','5','5'])

from collections import Counter
counts = Counter(a)

c = []

for ai , bi in zip(a,b):
   if counts[ai] == 5:
       c.append([ai,bi])
   elif counts[ai] == 1:
       c.append([ai,bi])
   else:
       None

print(c)
#[['12', '1'], ['12', '2'], ['12', '2'], ['12', '2'], ['12', '2'], ['23', '2']]

Is there a quick way so that my code can reformat the multiple output lists into a list that looks like:

#[('12', '12', '12', '12', '12', '23'), ('1', '2', '2', '2', '2', '2')]

so that each column in each list can have its own list.

Thank you!


Solution

  • What about that:

    import itertools
    
    c = [['12', '1'], ['12', '2'], ['12', '2'], ['12', '2'], ['12', '2'], ['23', '2']]
    
    merged = list(itertools.chain(*c))
    # merged = ['12', '1', '12', '2', '12', '2', '12', '2', '12', '2', '23', '2']
    
    split = [tuple(merged[::2]), tuple(merged[1::2])]
    # split = [('12', '12', '12', '12', '12', '23'), ('1', '2', '2', '2', '2', '2')]