2

我得到在 python3 中运行此代码时未定义的错误名称:

def main():
    D = {} #create empty dictionary
    for x in open('wvtc_data.txt'):
        key, name, email, record = x.strip().split(':')
        key = int(key) #convert key from string to integer
        D[key] = {} #initialize key value with empty dictionary
        D[key]['name'] = name
        D[key]['email'] = email
        D[key]['record'] = record

print(D[106]['name'])
print(D[110]['email'])
main()

你能帮我解决这个问题吗?

4

1 回答 1

3

您的变量D是函数的本地变量main,自然,外部代码看不到它(您甚至尝试在运行之前main访问它)。做类似的事情

def main():
    D = {} #create empty dictionary
    for x in open('wvtc_data.txt'):
        key, name, email, record = x.strip().split(':')
        key = int(key) #convert key from string to integer
        D[key] = {} #initialize key value with empty dictionary
        D[key]['name'] = name
        D[key]['email'] = email
        D[key]['record'] = record
    return D

D = main()
print(D[106]['name'])
print(D[110]['email'])
于 2013-10-10T00:29:02.110 回答