【问题标题】:Given a file, return a list of tuples representing the lines in the file on Python给定一个文件,返回一个元组列表,表示 Python 文件中的行
【发布时间】:2017-04-15 03:04:33
【问题描述】:

我有一个名为“sample.txt”的文件,其中包含以下内容:

1 city1 85 100 0.05
2 city2 80 100 0.05
3 city3 34 100 0.32

我想返回一个表示文件中行的元组列表。

项目的类型应为int,名称string除外 和体重float

所以结果会是这样的:

[(1, 'city1', 85, 100, 0.05), (2, 'city2', 80, 100, 0.05), (3, 'city3', 34, 100, 0.32)]

这是我到现在为止的代码:

def reader(filename):
    with open(filename) as f:
        arr = [tuple(line.split()) for line in f]
        return arr

print(reader("sample.txt"))

结果如下:

[('1', 'city1', '85', '100', '0.05'), ('2', 'city2', '80', '100', '0.05'), ('3', 'city3', '34', '100', '0.32')]

如您所见,所有项目都是strings,但我想将数字输入为int,将浮点数输入为float,就像上面显示的那样,但我被卡住了,我不知道是什么去做。

你能帮帮我吗?

感谢先进。 问候

【问题讨论】:

    标签: python file tuples


    【解决方案1】:

    你可以用对应的类型压缩,然后用它从字符串转换。

    def reader(filename):
        types = [int, str, int, int, float]
        with open(filename) as f:
            return [tuple(t(x) for t, x in zip(types, line.split())) for line in f]
    

    【讨论】:

    • 感谢您的建议!!
    【解决方案2】:
    def convert(x):
        try:
            a = float(x)
            b = int(a)
            return b if a == b else a
        except:
            return x
    
    def reader(filename):
        lines = []
        with open(filename) as f:
            for l in f:
                lines.append(tuple(map(convert, l.split())))
        return lines
    

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 1970-01-01
    • 2019-09-09
    • 2021-12-14
    • 2016-06-02
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    相关资源
    最近更新 更多