2016-12-16 52 views
1

我在尝试索引我的列表,然后分别调用每个列表中的最后两个值。
例如如何索引txt文件中的列表并调用索引值?

['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第一列表 (0,1)#from第二列表 (5,6)#from第三列表

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

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

(我一直在做尝试建立索引,但事实,那就是我的列表中的字符串已使其难以)

+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 
+0

非常感谢。这绝对有效。你是正确的这是一个csv文件,但我被告知把它作为一个txt文件(idk为什么)。我不知道你可以同时预制.split()和.strip()。另外我猜[-2:]保留列表中的最后两个字符?这对了解未来非常有帮助。 –

+0

它保留列表中的最后两个元素。所以'[ '苹果', '香蕉', '饼干', '油条'] [ - 2:] == [ '饼干', '油条']', – 2ps

+0

我有一个侧问题.....有一种调用最后两个值而不删除/删除列表的其余部分的方法?.....或者是我已经在做什么? –

0

使用

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

,但此行应旨在针对for循环,而不是告诉你在你的代码示例。