Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将函数应用于部分列表python_Python_Functional Programming - Fatal编程技术网

将函数应用于部分列表python

将函数应用于部分列表python,python,functional-programming,Python,Functional Programming,我想编写一个名为compress的函数,它接收一个列表、两个索引和一个函数,并将同一个列表中指定为“compressed”的两个元素与给定函数一起输出。我使用copy.deepcopy实现了这一点,如下所示: import copy def compress(l, i, j, f): r = copy.deepcopy(l) r[i] = f(r[i], r[j]) r.pop(j) return r 有没有更像蟒蛇的方法?或者可能是一种更“纯粹”的功能方式?功能方式是

我想编写一个名为compress的函数,它接收一个列表、两个索引和一个函数,并将同一个列表中指定为“compressed”的两个元素与给定函数一起输出。我使用copy.deepcopy实现了这一点,如下所示:

import copy
def compress(l, i, j, f):
   r = copy.deepcopy(l)
   r[i] = f(r[i], r[j])
   r.pop(j)
   return r

有没有更像蟒蛇的方法?或者可能是一种更“纯粹”的功能方式?

功能方式是重建一个新列表,而不是变异。为了简化操作,可以将其编写为生成器函数,使用一个简单的实用工具包装器从生成器构建列表:

def itercompress(source, first_index, second_index, compress_func):
    compressed = compress_func(source[first_index], source[second_index])
    for index, value in enumerate(source):
        if index == first_index:
            yield compressed
        elif index == second_index:
            continue
        else:
           yield value

def compress(source, first_index, second_index, compress_func):
    return list(itercompress(source, first_index, second_index, compress_func)
但不确定这是否会产生更好的性能。。。除了可能无用的
deepcopy
(好吧,这取决于压缩函数是否对其参数做了令人讨厌的事情,但我会说这是压缩函数作者的编程错误),您的代码只是缺少正确的命名,无法成为pythonic(“pythonic”不是指“花哨”或“聪明”或“优雅”,而是“正确”,“简单”和“可读”):


您需要深度复制吗?普通复制(
l.copy()
)有什么问题?除此之外(使用更明确的变量名)这很好。IDK关于pythonic,但是用一个以上的字母命名参数不会有什么坏处…你能把两个示例列表,然后一个示例输出吗?有很多方法可以解释“compressed”这个词是的,命名参数很好,我非常习惯只写我读过的代码。谢谢你的提醒。我想我是在问这可以通过“过滤器”或“地图”之类的工具来实现,但我的问题没有说清楚。无论如何,谢谢你的帮助:)
def compress(source, first_index, second_index, compress_func):
   result = source[:] # shallow copy
   result[first_index] = compress_func(result[first_index], result[last_index])
   result.pop(last_index)
   return result