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', 'Z@', '[>', '\\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最初の 2 つだけでなく、のすべてのペアをタプルに含めたい

4

2 に答える 2

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
于 2013-08-01T17:59:53.273 に答える