【发布时间】:2019-07-20 15:35:45
【问题描述】:
这是我的目标:
创建一个接受 2 个 CSV 文件并返回仅包含差异的第 3 个 CSV 文件的脚本。
我正在使用 Python 3.7.2。
这是我的代码:
def findFile1():
filename = ## prompts the user to select a .csv file.
with open(filename, 'r') as t1:
fileone = t1.readlines()
return fileone
def findFile2():
filename = ## prompts the user to select another .csv file.
with open(filename, 'r') as t2:
filetwo = t2.readlines()
return filetwo
def saveFile():
filename = ## prompts the user to name and choose a location to save a new .csv file.
fileone = findFile1() ##Here I would just like to readlines from the first CSV file. Not run the whole script again.
filetwo = findFile2() ##Here I would just like to readlines from the second CSV file. Not run the whole script again.
with open(filename, 'w') as outFile:
for line in filetwo:
if line not in fileone:
outFile.write(line)
我只想使用前 2 个函数的返回值,而不是再次调用整个函数。
更新: 我能够通过 Charles Duffy 的建议“导入 functools 并将 @functools.lru_cache() 行放在你的函数之上,所有未来的调用都将重用之前调用的结果”
解决了这个问题。【问题讨论】:
-
您当然可以更简洁地演示您的基本问题吗?我不明白为什么 tkinter 对于关于返回值/调用约定的问题是必要的(并且所有范围都超出了标题,代码与所述问题有什么关系并不明显);请注意,根据minimal reproducible example 指南,我们要求问题中的代码是尽可能短的工作示例,以演示特定、狭窄的问题。
-
...也就是说,在我看来,您想要做的是 memoize 函数调用的结果,因此它们会被记住并在其他调用中重用. “记忆化”是一个艺术术语,搜索起来可能很方便。
-
查尔斯,请原谅我。这是我第一次在这个网站上发布问题。请耐心等待我学习正确的礼仪。此外,我已经学习 python 大约一周了,所以我正在学习表达我的问题实际上需要哪些代码。感谢您为我指明了记忆的方向。我会追上那条小路,看看它会把我引向何方。
-
我对这个问题做了一些修改,希望能更清楚。谢谢你的建议。
-
如果你这样设计你的程序,你一定会在某个时间点运行你的函数。在
saveFile期间将函数的返回值定义为变量并没有错。如果你想更早地运行它,那么你必须定义全局变量来存储它们,或者创建一个类并将它们存储为属性。
标签: python python-3.x csv tkinter