首页 > 解决方案 > 如何返回在函数 A 中定义的列表以在 python 中的函数 B 中使用?

问题描述

我是编码和学习 Python 课程的新手。这是我们的第三个程序,教授已经开始希望我们避免使用全局变量。最初我的函数是通过定义 main 函数和列表 speedList-

speedList=[]
def main(): # Creates list of lists with offender's [name, speed, posted limit]
    file=open('speeds.txt', 'r')
    for line in file:
        stripped=line.strip()
        lineList=stripped.split()
        speedList.append(lineList)
    file.close()

在我的下一个函数 calcTicket() 中,我想在 for 循环中重用 speedList:

for list in speedList:
    speedOver=(int(list[1])-int(list[2]))
    if speedOver<5:
        a+=1
        fine=65
    elif 5<=speedOver<10:
        b+=1
        fine=85
    elif 10<=speedOver<15:
        c+=1
        fine=120
    elif 15<=speedOver<25:
        d+=1
        fine=150
    else:
        e+=1
        fine=200

为了避免使用全局变量,我重写了一点,并尝试在 main() 的开头定义 speedList 并在 main() 的末尾返回它以供 calcTicket() 使用,而不是全局定义 speedList。但是,这样做给了我

NameError: name 'speedList' is not defined.

我在这里遗漏了一些明显的东西吗?

编辑:重写代码-

def main(): # Creates list of lists with offender's [name, speed, posted limit]
    speedList=[]
    file=open('speeds.txt', 'r')
    for line in file:
        stripped=line.strip()
        lineList=stripped.split()
        speedList.append(lineList)
    file.close()
    return speedList

def calcTicket(): # Determines MPH over posted limit, appropriate fine, offenses per range. Prints table.
    a=b=c=d=e=0
    print("Name" + "MPH Over".rjust(22) + "Fine".rjust(10))
    print("-"*37)
    for list in speedList:
        speedOver=(int(list[1])-int(list[2]))
        if speedOver<5:
            a+=1
            fine=65
        elif 5<=speedOver<10:
            b+=1
            fine=85
        elif 10<=speedOver<15:
            c+=1
            fine=120
        elif 15<=speedOver<25:
            d+=1
            fine=150
        else:
            e+=1
            fine=200
        print(list[0]+str(speedOver).rjust(20-len(list[0]))+str(fine).rjust(15))
    print("-"*37)
    print("Tickets less than 5 MPH over: "+str(a))
    print("Tickets between 5 and 10 MPH over: "+str(b))
    print("Tickets between 10 and 15 MPH over: "+str(c))
    print("Tickets between 15 and 25 MPH over: "+str(d))
    print("Tickets greater than 25 MPH over: "+str(e))

main()
calcTicket()

标签: pythonlistfunction

解决方案


换个calcTicket说法;

calclTicket(speedList):
    ...

然后

something = main()
calcTicket(something)

推荐阅读