如何索引 txt 文件中的列表并调用索引值?

How do you index a list in a txt file and call on the indexed values?

我正在尝试为我的列表编制索引,然后分别调用每个列表中的最后两个值。
例如

['Ashe', '1853282.679', '1673876.66', '1 ', '2 \n']
['Alleghany', '1963178.059', '1695301.229', '0 ', '1 \n']
['Surry', '2092564.258', '1666785.835', '5 ', '6 \n']`    

我想要我的代码 return (1, 2) #来自第一个列表 (0, 1) #来自第二个列表 (5, 6) #来自第三个列表

我的代码目前包括:

def calculateZscore(inFileName, outFileName):
    inputFile = open(inFileName, "r")
    txtfile = open(outFileName, 'w')

    for line in inputFile:
        newList = (line.split(','))

    print newList

    inputFile.close()
    txtfile.close()


if __name__ == "__main__":
    main()    

(我一直在尝试建立索引,但我的列表中有一个字符串这一事实使它变得困难)

使用

newList = line.rstrip('\n').split(',')[-2:]

但是这一行应该针对 for 循环,而不是您在代码示例中显示的那样。

首先,不要在程序代码两边加上引号。其次,这里有一些快速指示:

def calculateZscore(inFileName, outFileName):
    # use with to open files to avoid having to `close` files
    # explicitly
    # inputFile = open(inFileName,"r")  
    # txtfile = open(outFileName, 'w')

    with open(inFileName, 'r') as inputFile, open(outFileName, 'w') as txtFile:
        for line in inputFile:
            newList = line.strip().split(',')
            last_two = newList[-2:] # this gets the last two items in the list  
            print last_two 



# indentation matters in python, make sure this line is indented all the way to the left, otherwise python will think it is part of 
# a different function and not the main block of running code
if __name__ == "__main__":
    main()

顺便说一句,您似乎正在阅读 CSV 文件。 python 具有您可能要考虑的内置 CSV 处理:

def calculateZscore(inFileName, outFileName):
    import csv
    with open(inFileName, 'r') as inputFile, open(outFileName, 'w') as txtFile:
        reader = csv.reader(inputFile)
        for newList in reader:
            last_two = newList[-2:] # this gets the last two items in the list  
            print last_two