Python,递归减少列表(组合/排列) [英] Python, recursively reduce a list (combinations/permutations)
问题描述
我正在尝试创建一个通用函数,以减少像这样的列表:
I'm trying to make a generic function that would reduce a list like so :
func(['a','b','c'],str.join) # --> ['a','b','c','ab','ac','bc','abc']
func(['a','b','c'],lambda: a,b:a+'x'+b) # --> ['a','b','c','axb','axc','bxc','axbxc']
我真的不知道该怎么做.我做了几次尝试,但都没有成功. 我很确定有一种方法可以减少它,但是我对使用此功能不太满意.这是一些尝试:
I don't really know how to do it. I did a few tries, but none was successful. I'm pretty sure there is a way to do it with reduce but i'm not very comfortable with the use of this function. Here are some attempts :
reduce(lambda a,b:[a,b,str(a)+str(b)],['a','b','c'])
reduce(str.join,['a','b','c'])
我认为我在某处缺少递归.
I think i'm missing a recursion somewhere.
我不是特别要求代码,欢迎任何帮助或建议.谢谢.
I'm not asking for code especially, any help or advice is welcomed. Thanks.
推荐答案
itertools.combinations
将为您提供一定长度的所有组合.我们对每个可能的子列表长度采用所有组合.然后,我们将您感兴趣的函数(lambda函数,在本例中为"x".join
)映射到每个生成的组合.
itertools.combinations
will give you all combinations of a certain length. We take all the combinations for each possible sublist length. We then map the function you were interested in (the lambda function, or in this case "x".join
) to each of the generated combinations.
>>> import itertools as it
>>> a = ['a','b','c']
>>> l = [map("x".join, list(it.combinations(a, l))) for l in range(1,len(a)+1)]
>>> l
[['a', 'b', 'c'], ['axb', 'axc', 'bxc'], ['axbxc']]
现在l
是我们要展平的列表的列表:
Now l
is a list of lists that we want to flatten:
>>> [ x for y in l for x in y]
['a', 'b', 'c', 'axb', 'axc', 'bxc', 'axbxc']
这篇关于Python,递归减少列表(组合/排列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!