Python 如何在txt文件中为列表编制索引并调用索引值?
我正在尝试为列表编制索引,然后分别调用每个列表中的最后两个值。Python 如何在txt文件中为列表编制索引并调用索引值?,python,wing-ide,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)#从
比如说
['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()
(我一直在尝试建立索引,但我的列表中有一个字符串这一事实使它变得很困难)使用
newList = line.rstrip('\n').split(',')[-2:]
但是这一行应该与for循环有关,而不是像您在代码示例中所显示的那样。首先,不要在程序代码周围加引号。其次,这里有一些快速提示:
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
我收到了一条关于无效文字签名的错误消息。那肯定管用。你是对的,这是一个csv文件,但我被告知要将其视为txt文件(idk为什么)。我不知道您可以同时执行.split()和.strip()。我猜[-2:]会保留列表中的最后两个字符吗?这对了解未来非常有帮助。它保留了列表中的最后两个元素。所以
['apple'、'banana'、'cookie'、'donut'][-2:]['cookie'、'donut']
,我有一个附带的问题……有没有一种方法可以调用最后两个值而不删除/删除列表中的其余部分?……或者这就是我已经在做的事情?@a_值得你已经在做了,如果你使用答案的话。“旧”列表是包含一行中所有元素的新列表,而仅包含最后两个元素的“新”列表是最后两个元素。