将文件读取为元组列表 [英] read file as list of tuples

查看:62
本文介绍了将文件读取为元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用python读取一个文件结果必须类似于(元组列表):

I want to read a file using python the result must be like (a list of tuples):

myList=[(1, 'assignment_1', 85,100', '0.05'),
        ('2', 'assignment_2', '80', '100', '0.05'),
        ('3', 'assignment_3', '95', '100', '0.05')]

文件包含:

1 assignment_1 85 100 0.05
2 assignment_2 80 100 0.05
3 assignment_3 95 100 0.05

我的代码:

inputfile=open(filename,"r")
myList=[]
for line in inputfile.readlines():
    tuples=line.split()
    myList.append(tuples)
print(myList)
fileinput.close()

结果

[['1', 'assignment_1', '85', '100', '0.05'],
 ['2', 'assignment_2', '80', '100', '0.05'], 
 ['3', 'assignment_3', '95', '100', '0.05']]

如何将项目转换为每种类型( int float ).我得到的是列表列表,而不是元组列表

How do I convert the items into each type(int, float). I got a list of lists, not a list of tuples

推荐答案

您可以在读取元素所在的行后立即将其转换为正确的类型:

You can convert the elements into the proper type immediately after the line they're in has been read:

from pprint import pprint

types = int, str, int, int, float
filename = 'assignments.txt'

with open(filename, "r") as inputfile:
    myList = []
    for line in inputfile:
        elements = tuple(t(e) for t,e in zip(types, line.split()))
        myList.append(elements)

pprint(myList)

输出:

[(1, 'assignment_1', 85, 100, 0.05),
 (2, 'assignment_2', 80, 100, 0.05),
 (3, 'assignment_3', 95, 100, 0.05)]

使用列表理解,可以更简洁地完成此操作:

This could be done even more succinctly using a list comprehension:

with open(filename, "r") as inputfile:
    myList = [tuple(t(e) for t,e in zip(types, line.split()))
                for line in inputfile]

还请注意,由于文件是可迭代的,逐行的,因此无需使用 readlines()一次将 file 的所有行读取到内存中.线.这在Python的教程中进行了描述在线文档.

Also note you don't need to use readlines() to read all the lines of a file into memory at once because files are iterable, line-by-line. This is described in the Tutorial in Python's online documentation.

这篇关于将文件读取为元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆