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

时间:2016-12-16 22:53:03

标签: python wing-ide

我试图索引我的列表,然后分别调用每个列表中的最后两个值 例如

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

我希望我的代码能够返回 (1,2)#from first list (0,1)#from第二个列表 (5,6)#from the third list

到目前为止我的代码包括:

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()    

(我一直在尝试编制索引,但事实上我的列表中有一个字符串一直很困难)

2 个答案:

答案 0 :(得分:1)

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

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 

答案 1 :(得分:0)

使用

group by

但是这一行应该与for循环有关,而不是你在代码示例中显示的那样。