我想从文件中读取行并在元组列表中打印内容 但我在转换过程中得到了两个逗号 我找不到删除更多逗号的方法。
代码:
def arrivalsFile(file_name):
"""
Reads part of an input file with the arrivals into a list of flights.
Requires: file_name, for arrivals, is a text file with the structure indicated in the quizz
Ensures: list of tuples, each corresponding to one flight
>>> arrivalsFile("arrivals_14_16.txt")
[('KLM75', 'Amsterdam', '14:35', '60', '50'), ('AF111', 'Paris', '14:20', '50', '64'), ('LH333', 'Frankfurt', '14:10', '112', '203'), ('KLM71', 'Madrid', '14:55', '120', '100'), ('TAP103', 'Salvador', '15:20', '174', '210'), ('LH123', 'Berlin', '15:10', '115', '210')]
"""
lista = []
inFile = open(file_name, "r")
for line in inFile:
if "Arrivals:" in line:
for line in inFile:
lista.append(tuple(line.split()))
inFile.close()
执行:
**********************************************************************
File "Z:\Documents\1415\airConveyorBeltsGroup11\readInput.py", line 9, in __main__.arrivalsFile
Failed example:
arrivalsFile("arrivals_14_16.txt")
Expected:
[('KLM75', 'Amsterdam', '14:35', '60', '50'), ('AF111', 'Paris', '14:20', '50', '64'), ('LH333', 'Frankfurt', '14:10', '112', '203'), ('KLM71', 'Madrid', '14:55', '120', '100'), ('TAP103', 'Salvador', '15:20', '174', '210'), ('LH123', 'Berlin', '15:10', '115', '210')]
Got:
[('KLM75,', 'Amsterdam,', '14:35,', '60,', '50'), ('AF111,', 'Paris,', '14:20,', '50,', '64'), ('LH333,', 'Frankfurt,', '14:10,', '112,', '203'), ('KLM71,', 'Madrid,', '14:55,', '120,', '100'), ('TAP103,', 'Salvador,', '15:20,', '174,', '210'), ('LH123,', 'Berlin,', '15:10,', '115,', '210')]
**********************************************************************
1 items had failures:
1 of 1 in __main__.arrivalsFile
***Test Failed*** 1 failures.
答案 0 :(得分:1)
lista.append(tuple(line.split(",")))
按,
而不是space
拆分。
答案 1 :(得分:0)
您需要在,
分割。
>>> line = 'KLM75, Amsterdam, 14:35, 60, 50'
>>> print(tuple(line.split(',')))
('KLM75', ' Amsterdam', ' 14:35', ' 60', ' 50')
如果您需要摆脱前导和尾随空格,请使用以下内容。
>>> print(tuple(element.strip() for element in line.split(',')))
('KLM75', 'Amsterdam', '14:35', '60', '50')
根据您的评论,您不想使用列表理解。好吧,从技术上讲,我使用了生成器表达式,而不是列表理解,但我修改了代码以显示你想要的内容。
lista = []
inFile = open(file_name, "r")
for line in inFile:
if "Arrivals:" in line:
data = []
for line in inFile:
for element in line.split(','):
data.append(element.strip())
lista.append(tuple(data))
inFile.close()
对于每一行,我们创建一个名为data
的新列表,将已剥离的元素附加到此列表,并在我们遍历该行中的所有元素后将此列表转换为元组。