python - 从字符串到元组的转换 - 双逗号

标签 python string file tuples

我想从文件中读取行并打印元组列表中的内容。
但我在转换过程中得到了两个逗号。
我无法找到删除逗号的方法。

代码:

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.

最佳答案

lista.append(tuple(line.split(",")))

,分割,而不是空格

关于python - 从字符串到元组的转换 - 双逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27228193/

相关文章:

Python Pandas 多条件赋值

r - 语料库中最常提到的国家;从摘要中提取国家名称 R

java - Java 中的 PrintWriter write() 与 print() 方法

python - 基于另一种阵列形状的零焊盘阵列

python - 使用 GLM 训练时获取 "H2OResponseError: ModelBuilderErrorV3" "Missing training frame"http_status = 412

python - 无和空字符串的 CSV 阅读器行为

c++ - 如何检查一个字符串是否表示一个正的非零整数?

windows - JavaScript - 提取文件夹名称

c - 从特定文件描述符读取输入

Python Selenium : TypeError: list indices must be integers or slices, 不是 WebElement