0

私はinput .txtでキーと値を取り、output.txtのように出力を生成しようとしています.現在は削除されます....私はPythonの実装を書くことができます.これを始める方法についての入力が必要です..

'''
INPUT(input.txt):-
#KEY    VALUE
353311 
344670 
332807 353314
338169 334478
334478 
353314 353311


OUTPUT(output.txt):-
KEY     VALUE
344670
332807 353314 353311
338169 334478
'''

with open('input.txt', 'rb') as f:
    mainlist = [line.strip() for line in f]
        print mainlist
4

2 に答える 2

1

NetworkX ライブラリを使用してそれを行う方法は次のとおりです。

import networkx as nx

inp = '''353311 
344670 
332807 353314
338169 334478
334478 
353314 353311'''.splitlines()

G = nx.DiGraph()
for line in inp:
    spl = line.split()
    if len(spl) == 1:
        G.add_node(spl[0])
    else:
        G.add_edge(spl[0], spl[1])

print nx.weakly_connected_components(G)
#[['353314', '332807', '353311'], ['338169', '334478'], ['344670']]
于 2013-06-14T08:52:47.627 に答える
1
from collections import OrderedDict
with open('abc') as f:
    dic = OrderedDict()
    seen = set()
    for line in f:
        spl = line.split() + [""]
        key ,v = spl[:2]
        if v in dic and dic[v] == [""]:
            del dic[v]
        for k1,v1 in dic.items():
            if key in v1:
               dic[k1].append(v)
               break
        else:
             dic[key] = [v]

with open('ouput.txt', 'w') as f:
    for k,v  in dic.items():
        f.write("{} {}\n".format(k," ".join(v)))

出力:

344670 
332807 353314 353311
338169 334478 
于 2013-06-13T23:53:50.750 に答える