使在Python的组合 [英] Making combinations in python

查看:120
本文介绍了使在Python的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四个值

age = 23
gender = "M"
city ="Delhi"
religion = "Muslim"

我需要这些安排的每一种组合与空值,例如 -

I need these arranged by every combination with empty values like -

23 * * *
23 M * *
23 M Delhi *
23 M Delhi Muslim
* M * *
* M Delhi *
* M Delhi Muslim
* * Delhi *
* * Delhi Muslim
* * * Muslim
* * * *

我需要这个安排的维数在列表中按升序排列。因此,组合用一个数值应该在最前面。我有一些30+的属性,所以我需要一个自动化的方式来做到这一点在Python

I need this arranged by the number of dimensions in ascending order in a list. So combinations with one value should be on top. I have some 30+ attributes, so i need an automated way to do this in Python

任何想法?

推荐答案

NPE的回答通过构建完整的解决问题在存储器子集的列表,然后分拣它。这需要O(2 N )的空间和O( N 2 2 N )的时间。如果这是不可接受的,那么这里有一个方法来生成在澳亚群( N 的)空间和O( N 的2 N )的时间。

NPE's answer solves the problem by constructing the full list of subsets in memory and then sorting it. This requires O(2n) space and O(n2 2n) time. If this is unacceptable, then here's a way to generate the subsets in O(n) space and O(n 2n) time.

from itertools import combinations

def subsets(s, placeholder = None):
    """
    Generate the subsets of `s` in order of size.
    Use `placeholder` for missing elements (default: None).
    """
    s = list(s)
    n = len(s)
    r = range(n)
    for i in range(n + 1):
        for c in combinations(r, i):
            result = [placeholder] * n
            for j in c:
                result[j] = s[j]
            yield result

>>> from pprint import pprint
>>> pprint(list(subsets([23, 'M', 'Delhi', 'Muslim'])))
[[None, None, None, None],
 [23, None, None, None],
 [None, 'M', None, None],
 [None, None, 'Delhi', None],
 [None, None, None, 'Muslim'],
 [23, 'M', None, None],
 [23, None, 'Delhi', None],
 [23, None, None, 'Muslim'],
 [None, 'M', 'Delhi', None],
 [None, 'M', None, 'Muslim'],
 [None, None, 'Delhi', 'Muslim'],
 [23, 'M', 'Delhi', None],
 [23, 'M', None, 'Muslim'],
 [23, None, 'Delhi', 'Muslim'],
 [None, 'M', 'Delhi', 'Muslim'],
 [23, 'M', 'Delhi', 'Muslim']]

这篇关于使在Python的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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