python列表递归逆序_Python,递归地减少一个列表(组合/排列)

这篇博客探讨了如何创建一个通用函数,该函数可以接受一个列表和一个结合函数,然后生成所有可能的组合。利用`itertools.combinations`,我们可以获取不同长度的子列表,并对每个子列表应用指定的函数,如字符串连接或自定义操作。通过这个方法,可以得到预期的输出,例如将字符连接或添加特定字符。博客中提供了具体的代码示例和解释。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

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 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']]

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']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值