提问者:小点点

将列表中的相同元素写入txt文件


我在dict中有一个列表,我提取了我需要的数据; “uni”,“gp”,“fr”,“rn”。

uni:1   gp:CC   fr:c2   rn:DS
uni:1   gp:CC   fr:c2   rn:PP
uni:1   gp:CC   fr:c2   rn:LL
uni:2   gp:CC   fr:c2   rn:DS
uni:2   gp:CC   fr:c2   rn:LL
.
.
.

上面是我写在txt文件中的输出,下面是代码:

for line in new_l:
    for key,value in line.items():
        if key == 'uni':
            unique.append(value)
        elif key == 'gp':
            pg.append(value)
        elif key == 'fr':
            rf.append(value)
        elif key == 'rn':
            rn.append(value)

with open('sampel1.list',mode='w') as f:
    for unique,gp,fr,rn in zip(uni,gp,fr,rn):
        f.write('uni:{uni}\t,gp:{gp}\t,fr:{fr}\t,rn:{rn}-\n'.format(uni=uni,gp=gp,fr=fr,rn=rn))

我想要的预期输出是合并具有不同值的'rn'和相同值的'unique','gp','fr'。

unique:1   gp:CC   fr:c2   rn:DS+PP+LL
unique:2   gp:CC   fr:c2   rn:DS+LL


共2个答案

匿名用户

下面是一种方法,我可以使用纯Python做类似的事情。 注意:这个特定的解决方案依赖于Python3.7命令保留插入顺序的事实:

from collections import defaultdict
# This will map the (uni, gp, fr) triplets to the list of merged rn values
merged = defaultdict(list)
for l in new_l:
    # Assuming these keys are always present; if not you will need to check
    # that and skip invalid entries
    key = (l['uni'], l['gp'], l['fr'])
    merged[key].append(l['rn'])

# Now if you wanted to write this to a file, say:
with open(filename, 'w') as f:
    for (uni, gp, fr), rn in merged.items():
        f.write(f'uni:{uni}\tgp:{gp}\tfr:{fr}\trn:{"+".join(rn)}\n')

注意,当我写“纯Python”时,我的意思是仅仅使用标准库。 在实践中,如果我处理表格数据,我可能会使用熊猫。

匿名用户

你需要学习一些算法和数据结构。 在这种情况下,您可以使用前3个元素创建一个唯一的散列,并根据该值追加或不追加最后一个元素。

示例:

lst = []
lst.append({'uni':1, 'gp':'CC', 'fr':'c2', 'rn':'DS'})
lst.append({'uni':1, 'gp':'CC', 'fr':'c2', 'rn':'PP'})
lst.append({'uni':1, 'gp':'CC', 'fr':'c2', 'rn':'LL'})
lst.append({'uni':2, 'gp':'CC', 'fr':'c2', 'rn':'DS'})
lst.append({'uni':2, 'gp':'CC', 'fr':'c2', 'rn':'PP'})
lst.append({'uni':3, 'gp':'CC', 'fr':'c2', 'rn':'DS'})


hash = {}

for line in lst:
   hashkey = str(line['uni'])+line['gp']+line['fr']
   if hashkey in hash.keys():
      hash[hashkey]['rn']+="+"+line['rn']
   else:
      hash[hashkey]={'uni':line['uni'], 'gp':line['gp'], 'fr':line['fr'], 'rn':line['rn']}

 print(hash)

结果:{“1CCC2”:{“uni”:1,“gp”:“cc”,“fr”:“c2”,“rn”:“ds+pp+ll”},“2CCC2”:{“uni”:2,“gp”:“cc”,“fr”:“c2”,“rn”:“ds+pp”},“3CCC2”:{“uni”:3,“gp”:“cc”,“fr”:“c2”,“rn”:“ds”}}