1

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

['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) #从第一个列表 (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()    

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

4

2 回答 2

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 
于 2016-12-16T23:37:20.230 回答
0

利用

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

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

于 2016-12-16T23:35:11.560 回答