python - 如何对 txt 文件中的列表进行索引并调用索引值?

标签 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) #来自第一个列表 (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()    

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

最佳答案

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

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 

关于python - 如何对 txt 文件中的列表进行索引并调用索引值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41193547/

相关文章:

python - 在 Wing101 中切换到 Python 3.6

python - 为什么 2**100 比 math.pow(2,100) 快这么多?

python - pickle 过程是确定性的吗?

python - 如何在 Python OpenCV 中增加图像的对比度

python - Django - 将异常传递给调试器

python - 如何定义具有条件作为输入的函数?

Python lmfit - 线性回归中的截距估计为何取决于起始值?

python - 翼IDE + Python 2.4 : no module named functools

python - 为 MCEdit 的 python 脚本设置 WingIDE 环境