我试图弄清楚如何将一个函数的结果传递给同一脚本中的另一个函数。我已经测试过 CreateDict 函数,它可以正常工作。我无法将结果用作 CreateHumanUsrNameDict 的输入。我收到的以下错误是 CreateHumanUsrNameDict(UsrDict) NameError: 名称 “ UsrDict” 是 未已定义
import csv
def CreateDict(filename):
UsrDict = {}
with open(filename) as csvfile:
readCSV = csv.reader(csvfile, delimiter=':')
for row in readCSV:
UsrDict[row[0]]=row[1]
return UsrDict
def CreateHumanUsrNameDict(UsrDict):
HumanUsrDict={}
for k, v in HumanUsrDict.items():
if v == len(4):
HumanUsrDict[k:v]
print(HumanUsrDict)
if __name__=='__main__':
CreateDict('Book1.csv')
CreateHumanUsrNameDict(UsrDict)
答案 0 :(得分:0)
调用CreateDict时,需要将返回值分配给变量UsrDict。试试这个:
import csv
def CreateDict(filename):
UsrDict = {}
with open(filename) as csvfile:
readCSV = csv.reader(csvfile, delimiter=':')
for row in readCSV:
UsrDict[row[0]]=row[1]
return UsrDict
def CreateHumanUsrNameDict(UsrDict):
HumanUsrDict={}
for k, v in HumanUsrDict.items():
if v == len(4):
HumanUsrDict[k:v]
print(HumanUsrDict)
if __name__=='__main__':
UsrDict = CreateDict('Book1.csv')
CreateHumanUsrNameDict(UsrDict)