【问题标题】:how to get input in a specific order from a file in python如何从python中的文件中以特定顺序获取输入
【发布时间】:2024-05-20 16:05:02
【问题描述】:

我有一个包含许多测试用例的文件,我想将它们作为我的输入, 文件的容器是这样的

1 232 4343
2 343 5454
3 545 6556
...

我想要一个地图列表,这样输入就会像这样保存:

[[232,4343], [343, 5454], [545,6556] , ...]

第一个输入(行数)很容易获得,只需使用列表的列表索引,但我怎样才能获得其他输入并将它们保存到列表列表中?
我正在使用 python 3.6.5

【问题讨论】:

    标签: python file input testcase


    【解决方案1】:

    试试这个:

    with open(filename,'r') as f:
        l=[list(map(int,i.rstrip().split()[1:])) for i in f]
    

    现在:

    print(l)
    

    是:

    [[232,4343], [343, 5454], [545,6556]]
    

    或者更快地使用 Pandas:

    import pandas as pd
    df=pd.read_csv(filename,sep='\s+',header=None,index_col=0)
    print(df.values.tolist())
    

    输出:

    [[232, 4343], [343, 5454], [545, 6556]]
    

    更新:

    with open(filename,'r') as f:
        l=[list(map(int,i.rstrip().split())) for i in f]
    

    输出:

    [[1, 232, 4343], [2, 343, 5454], [3, 545, 6556]]
    

    或者使用熊猫:

    import pandas as pd
    df=pd.read_csv(filename,sep='\s+',header=None)
    print(df.values.tolist())
    

    这样做需要更少的代码......

    【讨论】:

    • @brunodesthuilliers 完成!
    • @pgh 很高兴为您提供帮助,:-),????,如果可行,请接受 :-)
    • 如果我希望我的索引也出现在列表中怎么办,例如 [[1,232,4343] , [2,343,5454] ,....]。我试图修改代码,但我没有成功修改它。如果你能帮助我,我会很高兴