我正在尝试从1个数据文件创建5个列表,错误我一直得到“航空公司未定义”的状态,但这是我在函数中定义的第一件事,这怎么可能?如何正确创建航空公司列表,到达时间,出发时间,价格和航班号?
USAir,1269,6:15,10:57,210
Delta,5138,16:20,22:10,212
UNITED,6001,14:12,20:50,217
Delta,5054,12:30,20:22,227
UNITED,5949,9:30,14:43,264
JetBlue,1075,17:00,20:06,280
Delta,1263,6:00,11:30,282
Delta,3824,9:00,14:45,282
USAir,1865,16:55,21:33,300
USAir,3289,18:55,23:41,300
USAir,1053,8:00,13:02,300
USAir,2689,12:55,18:09,300
USAir,3973,9:25,14:00,302
USAir,3267,11:30,16:13,302
USAir,3609,13:25,18:28,302
USAir,3863,15:35,20:54,302
USAir,3826,17:45,23:19,302
USAir,1927,7:00,12:53,302
Delta,3601,12:00,17:29,307
Delta,4268,7:15,12:46,307
UNITED,4676,6:00,10:45,321
UNITED,4103,11:00,16:16,321
USAir,3139,11:51,16:29,332
JetBlue,475,7:30,10:42,340
USAir,3267,11:30,18:15,367
UNITED,2869,16:55,21:33,406
UNITED,2865,6:15,10:57,406
UNITED,2729,8:00,13:02,406
UNITED,2645,7:00,12:53,445
我正在使用的代码是
def getFlights():
airlines = []
flightNums = []
depTimes = []
arriveTimes = []
prices = []
fname = input("Enter name of data file: ")
infile = open(fname, 'r')
line = infile.readline()
line = line.strip()
while line != "":
line = line.strip()
airline, flightNum, depTime, arriveTime, price = line.split(',')
airlines.append(airline)
flightNums.append(flightNum)
depTimes.append(depTime)
arriveTimes.append(arriveTime)
prices.append(price)
line = infile.readline()
line = line.strip()
infile.close()
return airlines, flightNums, depTimes, arriveTimes, prices
getFlights()
print(airlines, flightNums, depTimes, arriveTimes, prices)
答案 0 :(得分:1)
函数内部的局部变量在函数调用之外是不可访问的。如果要使用返回的getFlights
值,则必须将它们分配给调用上下文中的变量。
(airlines, flightNums, depTimes, arriveTimes, prices) = getFlights()
print(airlines, flightNums, depTimes, arriveTimes, prices)
答案 1 :(得分:0)
b4hand所说的是正确的,然而,Pythonic这样做的方法是使用csv.reader
和with
语句,例如:
import csv
filename = input('Enter filename: ')
with open(filename, 'rb') as fin:
csvin = csv.reader(fin)
airlines, flightNums, depTimes, arriveTimes, prices = zip(*csvin)