【问题标题】:How to Read a file into a 2D Array in Python?如何在 Python 中将文件读入二维数组?
【发布时间】:2017-03-09 22:41:11
【问题描述】:

所以我有一个文件 (user.txt) 包含这个

James, 10, Orange 
Andrew, 16, Yellow 
Graham, 23, Pink

我想这样做,以便我可以将文件读入一个嵌套列表,这样我就可以拥有

print(user[0][1])
#10

我尝试过:

with open("user.txt") as file:
    user = [line.split(", ") for line in file.readlines()]

print(user[0][1])

但是我得到'IndexError:列表索引超出范围'

希望有人能帮忙

【问题讨论】:

标签: python arrays


【解决方案1】:
with open("file location") as file:
    user = [line.rstrip("\n").split(", ") for line in file]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    相关资源
    最近更新 更多