Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.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 给定一个iterable,如何在每个可能的组合中应用函数?_Python - Fatal编程技术网

Python 给定一个iterable,如何在每个可能的组合中应用函数?

Python 给定一个iterable,如何在每个可能的组合中应用函数?,python,Python,给定iterable[A,B,C]和函数fx,我想得到以下结果: [ A, B, C] [ A, B, f(C)] [ A, f(B), C] [ A, f(B), f(C)] [f(A), B, C] [f(A), B, f(C)] [f(A), f(B), C] [f(A), f(B), f(C)] 不幸的是,我在itertools模块中没有找到任何合适的工具。您可以这样使用 def f(cha

给定iterable[A,B,C]和函数fx,我想得到以下结果:

[  A,     B,     C]  
[  A,     B,   f(C)]  
[  A,   f(B),    C]
[  A,   f(B),  f(C)]
[f(A),    B,     C]
[f(A),    B,   f(C)]
[f(A),  f(B),    C]
[f(A),  f(B),  f(C)]
不幸的是,我在itertools模块中没有找到任何合适的工具。

您可以这样使用

def f(char):
    return char.lower()

iterable = ["A", "B", "C"]
indices = range(len(iterable))
from itertools import combinations
for i in range(len(iterable) + 1):
    for items in combinations(indices, i):
        print [f(iterable[j]) if j in items else iterable[j] for j in range(len(iterable))]
输出

说明:

为L中的每个项目调用f以生成fL

使用zip将两个列表压缩成对

>>> zip(L, fL)
[('A', 'a'), ('B', 'b'), ('C', 'c')]
使用itertools.product获取这些元组的笛卡尔乘积

相当于

product(*[('A', 'a'), ('B', 'b'), ('C', 'c')])
product(('A', 'a'), ('B', 'b'), ('C', 'c'))
这相当于

product(*[('A', 'a'), ('B', 'b'), ('C', 'c')])
product(('A', 'a'), ('B', 'b'), ('C', 'c'))
在该产品上循环,正好给出我们需要的结果

import itertools
def func_combinations(f, l):
    return itertools.product(*zip(l, map(f, l)))
演示:


此函数首先为输入的每个元素计算一次f。然后,它使用zip将输入和f值列表转换为输入输出对列表。最后,它使用itertools.product生成选择输入或输出的各种可能方式。

输出应包含输入中的所有元素,即:[a',B',C'],而不仅仅是['a']。这是可行的,但它计算的f远远超过了需要,这可能是一个问题,取决于f有多贵。接受你的第二个解决方案的答案。我相信从逻辑的角度来看,它也更有意义。如果你把答案编辑成只有后一种更深入描述的解决方案,那就太酷了。
product(('A', 'a'), ('B', 'b'), ('C', 'c'))
import itertools
def func_combinations(f, l):
    return itertools.product(*zip(l, map(f, l)))
>>> for combo in func_combinations(str, range(3)):
...     print combo
...
(0, 1, 2)
(0, 1, '2')
(0, '1', 2)
(0, '1', '2')
('0', 1, 2)
('0', 1, '2')
('0', '1', 2)
('0', '1', '2')