python - 如何返回在函数 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()
解决方案
换个calcTicket
说法;
calclTicket(speedList):
...
然后
something = main()
calcTicket(something)
推荐阅读
- python - 使用 Pandas 将 CSV 递归编辑到子目录
- python - 得到了意想不到的关键字参数形状
- angular - 如何重写我的打字稿代码,使其不会触发 http 请求?
- python - 多个 if 条件给了我错误的答案
- spring-boot - 当我想我尝试了很多解决方案时,如何在 Kotlin 和 Gradle 项目中使用 DevTools?
- python - 为什么 tf.matmul 不能与转置张量一起使用?
- css - 如何在详细信息上方设置 Woocommerce 产品图片
- excel - 根据多个单元格值隐藏或取消隐藏工作表
- python - 无法在scrapy的解析回调中发送请求
- python - 过大的预测 MLPRegressor