根据其他列表对值进行分组

时间:2015-07-25 04:41:41

标签: python

根据组名对列表值进行分组:

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

out文本文件应如下所示:

a 1 4
b 2 5 6
c 3
with open ('out.txt','w') as fo:
   fo.write(group + str(values) + '\n')

1 个答案:

答案 0 :(得分:2)

您可以使用zip函数和dict.setdefault方法在字典中对值进行分组,然后将项目写入文件:

>>> 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')