2013-08-01 3 views
0
def get_key(file): 
    '''(file open for reading) -> tuple of objects 

     Return a tuple containing an int of the group length and a dictionary of 
     mapping pairs. 
    ''' 

    f = open(file, 'r') 
    dic = f.read().strip().split() 
    group_length = dic[0] 
    dic[0] = 'grouplen' + group_length 
    tup = {} 
    tup['grouplen'] = group_length 
    idx = 1 
    dic2 = dic 
    del dic2[0] 
    print(dic2) 

    for item in dic2: 
     tup[item[0]] = item[1] 
     print(tup) 


     return tup 

결과를 각 항목에 대해 뭔가를 적용하는 방법입니다 : {'grouplen': '2', '"': 'w'} DIC 2는 다음과 같습니다목록에

['"w', '#a', '$(', '%}', '&+', "'m", '(F', ')_', '*U', '+J', ',b', '-v', '.<', '/R', '0=', '1$', '2p', '3r', '45', '5~', '6y', '7?', '8G', '9/', ':;', ';x', '<W', '=1', '>z', '?"', '@[', 'A3', 'B0', 'CX', 'DE', 'E)', 'FI', 'Gh', 'HA', 'IN', 'JS', 'KZ', 'L\\', 'MP', 'NC', 'OK', 'Pq', 'Qn', 'R2', 'Sd', 'T|', 'U9', 'V-', 'WB', 'XO', 'Yg', '[email protected]', '[>', '\\V', ']%', '^`', '_T', '`,', 'aD', 'b#', 'c:', 'dM', 'e^', 'fu', 'ge', 'hQ', 'i7', 'jY', 'kc', 'l*', 'mH', 'nk', 'o4', 'p8', 'ql', 'rf', 's{', 'tt', 'uo', 'v.', 'w6', 'xL', 'y]', 'zi', '{s', '|j', '}&', "~'"] 

내가 튜플은 첫번째뿐만 아니라 dic2의 모든 쌍을 포함 할 두

+1

dedent retun의 대가리를 반환 만 루프 종료 후 실행 – rlms

답변

7

너는 들여 쓰기가 필요하지 않다.return이다. 에 되 돌리면 첫 번째 반복에서 루프가됩니다. 대신

:

for item in dic2: 
    tup[item[0]] = item[1] 
    print(tup) 

    return tup 

는 수행

for item in dic2: 
    tup[item[0]] = item[1] 
    print(tup) 

return tup 

이제 제대로 작동의 초기 기능을 종료하지 않는 루프를 할 수 있습니다.

파일 형식에 따라 파일을 읽는 더 좋은 방법이있을 수 있습니다. 각 항목이 새 행에 나열되면 다음과 같이 읽습니다.

def get_key(file): 
    '''(file open for reading) -> tuple of objects 

     Return a tuple containing an int of the group length and a dictionary of 
     mapping pairs. 
    ''' 

    with open(file, 'r') as f: 
     grouplen = next(f) # first line 
     res = {'grouplen': int(grouplen)} 

     for line in f: 
      res[line[0]] = line[1] 

    return res 
2

(파이썬에서 indentation이 핵심입니다.

for item in dic2: 
    ... 
    return tup 

이것은 들여 쓰기 후에 들여 쓰기되기 때문에 return 문이 for 루프 안에 들어갑니다. 여기

for item in dic2: 
    ... 
return tup 

, 들여 쓰기 같은 수준에있는 및 반환 선언문 이후, return 문 따라서 전체 튜플에게