[英]Given an iterable, how to apply a function in every possible combination?
Given the iterable [A, B, C]
and the function f(x)
I want to get the following: 给定可迭代的
[A, B, C]
和函数f(x)
我想得到以下内容:
[ 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)]
Unfortunately I didn't find anything suitable in the itertools module. 不幸的是,我在itertools模块中找不到合适的东西。
>>> from itertools import product
>>> L = ["A", "B", "C"]
>>> def f(c): return c.lower()
...
>>> fL = [f(x) for x in L]
>>> for i in product(*zip(L, fL)):
... print i
...
('A', 'B', 'C')
('A', 'B', 'c')
('A', 'b', 'C')
('A', 'b', 'c')
('a', 'B', 'C')
('a', 'B', 'c')
('a', 'b', 'C')
('a', 'b', 'c')
Explanation: 说明:
Call f
for each item in L
to generate fL
对
L
每个项目调用f
以生成fL
>>> fL
['a', 'b', 'c']
Use zip
to zip the two lists into pairs 使用
zip
将两个列表压缩成对
>>> zip(L, fL)
[('A', 'a'), ('B', 'b'), ('C', 'c')]
Take the cartesian product of those tuples using itertools.product
使用
itertools.product
提取那些元组的笛卡尔积。
product(*zip(L, fL))
is equivalent to 相当于
product(*[('A', 'a'), ('B', 'b'), ('C', 'c')])
and that is equivalent to 那相当于
product(('A', 'a'), ('B', 'b'), ('C', 'c'))
looping over that product, gives exactly the result we need. 遍历该产品,可以准确给出我们需要的结果。
You can use itertools.combinations
, like this 您可以像这样使用
itertools.combinations
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))]
Output 输出量
['A', 'B', 'C']
['a', 'B', 'C']
['A', 'b', 'C']
['A', 'B', 'c']
['a', 'b', 'C']
['a', 'B', 'c']
['A', 'b', 'c']
['a', 'b', 'c']
import itertools
def func_combinations(f, l):
return itertools.product(*zip(l, map(f, l)))
Demo: 演示:
>>> 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')
This function first computes f
once for every element of the input. 此函数首先为输入的每个元素计算一次
f
。 Then, it uses zip
to turn the input and the list of f
values into a list of input-output pairs. 然后,它使用
zip
将输入和f
值列表转换为输入输出对列表。 Finally, it uses itertools.product
to produce each possible way to select either input or output. 最后,它使用
itertools.product
产生选择输入或输出的每种可能方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.