简体   繁体   English

如何为列表中的每个项目应用内容

[英]How to apply something for every item in a list

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

The result is: {'grouplen': '2', '"': 'w'} The dic 2 is: 结果为: {'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', '}&', "~'"]

I want the tuple to contain all the pairs in dic2 , not just the first two 我希望元组包含dic2所有对,而不仅仅是前两个

You need to de-indent the return statement. 您需要使return语句缩进缩进 You are returning in the loop, so in the first iteration. 正在重返环,所以在第一次迭代。

Instead of: 代替:

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

    return tup

do: 做:

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

return tup

Now you let the loop do it's work properly and not end the function early. 现在,让循环完成它的工作,而不是尽早结束该功能。

There probably is a better way to read your file, depending on the format of the file. 根据文件的格式,可能有更好的读取文件的方法。 If each entry is listed on a new line, I'd read it as follows: 如果每个条目都在新行中列出,我将按以下方式阅读:

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

in python, indendation is the key. 在python中,约束是关键。

for item in dic2:
    ...
    return tup

this makes the return statement fall inside the for loop since the return is indented after the for indentation. 由于return在for缩进之后缩进,因此这使return语句落入for循环内。

for item in dic2:
    ...
return tup

here, since the for and the return statement are at the same level of indentation, the return statement is executed only after the loop ends, thus returning the whole tuple 在这里,由于for和return语句的缩进级别相同,因此return语句仅在循环结束后才执行,因此返回整个元组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM