什么是Python代码中的字典理解技术和_?

时间:2015-12-13 21:02:29

标签: python dictionary

在下面的代码中,循环中的_ for是什么?我们为什么用它?它是语言不可知的吗?

此外,行是什么

dic = {key:value for (key, value) in zip(headers, row) }

在做什么?

def parse_file(datafile):
    result = []
    f = open(datafile)

    # loop over the first 11 lines of a file, split() each line
    # and produce a list of stripped() values
    rows = []
    for _ in xrange(11):
        line = f.readline()
        row  = [ value.strip() for value in line.split(',') ] 
        rows.append(row)

    f.close()

    # pop() the first row from rows and use it as headers
    headers = rows.pop(0)

    for row in rows:
        # dic is a dictionary of header-value pairs for each row, 
        # produced by using the builtin zip() function
        # and the dictionary comprehension technique.
        dic = { key:value for (key, value) in zip(headers, row) }

        result.append(dic)        
    return result

0 个答案:

没有答案