生成列表的所有有序组合,其中每个组合包括所有项目 [英] Generate all ordered combinations of a list, where each combination includes all items

查看:80
本文介绍了生成列表的所有有序组合,其中每个组合包括所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

生成列表的所有组合的最佳方法是什么,其中每种组合都包含列表中的每个项目,而您可以组合其他项目.

Whats the best way to generate all combinations of a list, where each combinations contains every item from the list and where you can combine other items.

例如,对于列表['a','b','c'],我喜欢生成:

For example, for a list ['a','b','c'], I like to generate:

['a','b','c']
['ab','c']
['a','bc']
['abc']

我发现它有点类似于: Python:生成所有有序的列表的组合.但这只关心切片.我想要所有从列表中取出每个项目的组合.是否有来自itertools的内置函数可用于生成答案?

I find it a bit similar to: Python: Generating all ordered combinations of a list. But this one only cares about the slices. I want all the combinations that takes every item from the list. Is there a built in function from itertools that can be used to generate the answer?

列表也可以是数字,可以有重复的值.例如:[1,2,1]应生成:

The list could also be numbers, that could have duplicates values. For example: [1,2,1] should generate:

[1,2,1]
[12,1]
[1,21]
[121]

我可以尝试使用链接中的代码,但是我不会生成项目的组合,而是会基于列表的索引生成组合.我将以0开头的所有组合都放在这里,然后寻找下一个项目,并寻找以该项目开始的所有组合,依此类推.我认为那不会很有效.

I could try to use the code from the link, but instead of generating combinations of the items, I would generate the combinations base on the index of the list. Where I take all combinations that start with 0, then look for the next item and look for all combinations that start with that item and so on. I dont think that would be efficient though.

推荐答案

您可以认为字符串中的两个相邻字符是分隔"或串联"的.使用itertools.product(),您可以生成两个字符之间的所有分隔/串联组合,然后使用一个简单的函数根据以下信息生成字符串列表:

You can think of two adjacent characters in your string as being either "separated" or "concatenated". Using itertools.product() you can generate all combinations of separated/concatenated between two characters and then use a simple function to generate a list of strings from this information:

import itertools

l = ['a','b','c']

def generate_combination(source, comb):
    res = []
    for x, action in zip(source,comb + (0,)):
        res.append(x)
        if action == 0:
            yield "".join(res)
            res = []

print [list(generate_combination(l,c)) 
       for c in itertools.product((0,1), repeat=len(l)-1)]

这不适用于数字,除非您首先将它们转换为字符串.

This doesn't work for numbers though unless you convert them to strings first.

这篇关于生成列表的所有有序组合,其中每个组合包括所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆