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
Run Code Online (Sandbox Code Playgroud)
结果是:{'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', '}&', "~'"]
Run Code Online (Sandbox Code Playgroud)
我希望元组包含所有对dic2,而不仅仅是前两个
您需要对该语句进行去缩进return.你在循环中返回,所以在第一次迭代中.
代替:
for item in dic2:
tup[item[0]] = item[1]
print(tup)
return tup
Run Code Online (Sandbox Code Playgroud)
做:
for item in dic2:
tup[item[0]] = item[1]
print(tup)
return tup
Run Code Online (Sandbox Code Playgroud)
现在你让循环正常工作,而不是提前结束功能.
根据文件的格式,可能有更好的方法来读取文件.如果每个条目都列在新行上,我会按如下方式阅读:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |