Python,递归减少列表(组合/排列)

编程入门 行业动态 更新时间:2024-10-06 14:37:15
本文介绍了Python,递归减少列表(组合/排列)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试创建一个通用函数,以减少像这样的列表:

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.

推荐答案

itertoolsbinations将为您提供一定长度的所有组合.我们对每个可能的子列表长度采用所有组合.然后,我们将您感兴趣的函数(lambda函数,在本例中为"x".join)映射到每个生成的组合.

itertoolsbinations 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(itbinations(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,递归减少列表(组合/排列)

本文发布于:2023-11-30 15:28:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650510.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   组合   排列   列表   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!