根据组名对列表值进行分组:
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')
答案 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')