有没有一种更为python的方法来做以下事情(请原谅半伪代码)?你知道吗
from copy import deepcopy
# Create a copy of a list edit an element within it
# then run a function using the new copy of the list
actuallist = [some data]
answer = 0
for i in len(actuallist):
temp = deepcopy(actuallist)
temp[i] = temp[i] + something
tempplus = DoSomething(temp)
temp = deepcopy(actuallist)
temp[i] = temp[i] - something
tempminus = DoSomething(temp)
answer += OneMoreThing(tempplus, tempminus)
如果
DoSomething
没有改变列表,您可以这样做:但是,不管我们是使用列表的深度副本,还是仅使用片段,我们都应该将该公共功能捆绑到一个函数中:
此时,我们可以将该循环重写为:
此时,您实际上可以将其重写为生成器表达式,使用
sum
进行求和。你知道吗不过,一下子要做的事情有点多。我可能会建议使用另一个函数。你知道吗
基于您给出的通用示例名称,我不理解您的函数的性质,因此我不能确定如何最好地对其进行分组。你可以这样做:
有了这些非常通用的名字,我认为这实际上可能没有你的例子那么清楚。但是,我假设您可以为特定的问题域选择一些逻辑名称,这将使这个问题域更具自文档性。你知道吗
相关问题 更多 >
编程相关推荐