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,而不仅仅是前两个

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 回答
2

在 python 中,缩进是关键。

for item in dic2:
    ...
    return tup

这使得 return 语句落入 for 循环,因为 return 在 for 缩进之后缩进。

for item in dic2:
    ...
return tup

这里,由于for和return语句在同一级缩进,所以return语句只有在循环结束后才执行,从而返回整个元组

于 2013-08-01T18:06:16.263 回答