2010-08-18 2 views
0

파이썬에서 단일 항목 라인에 많은 항목으로 목록을 변환 :나는이에서 텍스트 파일에 라인을 변환 할

animal cat, mouse, dog, horse 
numbers 22,45,124,87 

이에 :

animal cat 
animal mouse 
animal dog 
animal horse 
numbers 22 
numbers 45 
numbers 124 
numbers 87 

어떻게이 변환을 할 것 파이썬으로?

감사합니다.

답변

0

collections.defaultdict을 사용하십시오.

비슷한 질문을 위해 SO를 검색 할 수 있습니다. 지퍼

4
with open('thefile.txt') as fin: 
    with open('result.txt') as fou: 
    for line in fin: 
     key, values = line.split(None, 1) 
     vs = [x.strip() for x in values.split(',')] 
     for v in vs: 
      fou.write('%s %s\n' % (key, v)) 
0

이 같이 할 수있는 :

inp="""animal cat, mouse, dog, horse 
numbers 22,45,124,87 
""" 
for line in inp.splitlines(): 
    key,data = line.split(None,1) 
    print '\n'.join("%s%8s" % line 
        for line in zip([key.strip()] * (data.count(',')+1), 
            (item.strip() for item in data.split(','))))