Borys
Borys

Reputation: 1423

Grouping values based on other list

Grouping the list values according to group names:

groups = ['a','b','c','a','b','b']
values = [1, 2, 3, 4, 5, 6]

The out text file should look like this:

a 1 4
b 2 5 6
c 3

with open ('out.txt','w') as fo:
   fo.write(group + str(values) + '\n')

Upvotes: 0

Views: 46

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

You can use zip function and dict.setdefault method to group your values in a dictionary then write the items to file :

>>> groups = ['a','b','c','a','b','b']
>>> values = [1, 2, 3, 4, 5, 6]
>>> 
>>> d={}
>>> 
>>> for i,j in zip(groups,values):
...   d.setdefault(i,[]).append(j)
... 
>>> d
{'a': [1, 4], 'c': [3], 'b': [2, 5, 6]}



with open ('out.txt','w') as fo:
   for k,v in d.items():
        fo.write(k +'  '+ ' '.join(map(str,values)) + '\n')

Upvotes: 2

Related Questions