gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:52:07 35 4
gpt4 key购买 nike

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

['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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com