gpt4 book ai didi

Python:从文件读入列表

转载 作者:太空宇宙 更新时间:2023-11-04 10:40:08 26 4
gpt4 key购买 nike

我希望我的程序从一个 .txt 文件中读取,该文件的行中的数据排列如下:NUM NUM NAME NAME NAME。我如何将它的行读入列表,以便每一行都成为列表的一个元素,并且每个元素的前两个值是整数,其他三个值是字符串?

所以文件的第一行:1 23 Joe Main Sto 应该变成 lst[0] = [1, 23, "Joe", "Main", "Sto"]

我已经有了这个,但它不能完美地工作,我相信一定有更好的方法:

read = open("info.txt", "r")
line = read.readlines()
text = []
for item in line:
fullline = item.split(" ")
text.append(fullline)

最佳答案

使用str.split()没有参数自动为您折叠和删除空格,然后将 int() 应用于前两个元素:

with open("info.txt", "r") as read:
lines = []
for item in read:
row = item.split()
row[:2] = map(int, row[:2])
lines.append(row)

注意这里我们直接遍历文件对象,不需要先将所有行读入内存。

关于Python:从文件读入列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21137942/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com