在python中组合

Adi*_*ngh 1 python sorting algorithm combinations combinatorics

我有四个值

age = 23
gender = "M"
city ="Delhi"
religion = "Muslim"
Run Code Online (Sandbox Code Playgroud)

我需要通过每个组合排列这些空值,如 -

23 * * *
23 M * *
23 M Delhi *
23 M Delhi Muslim
* M * *
* M Delhi *
* M Delhi Muslim
* * Delhi *
* * Delhi Muslim
* * * Muslim
* * * *
Run Code Online (Sandbox Code Playgroud)

我需要在列表中按升序排列维数.因此,具有一个值的组合应该位于顶部.我有30多个属性,所以我需要一种自动化的方法在Python中执行此操作

有任何想法吗 ?

NPE*_*NPE 5

以下内容如何:

In [21]: attrib = (23, "M", "Delhi", "Muslim")

In [25]: comb = list(itertools.product(*((a, None) for a in attrib)))

In [26]: comb
Out[26]: 
[(23, 'M', 'Delhi', 'Muslim'),
 (23, 'M', 'Delhi', None),
 (23, 'M', None, 'Muslim'),
 (23, 'M', None, None),
 (23, None, 'Delhi', 'Muslim'),
 (23, None, 'Delhi', None),
 (23, None, None, 'Muslim'),
 (23, None, None, None),
 (None, 'M', 'Delhi', 'Muslim'),
 (None, 'M', 'Delhi', None),
 (None, 'M', None, 'Muslim'),
 (None, 'M', None, None),
 (None, None, 'Delhi', 'Muslim'),
 (None, None, 'Delhi', None),
 (None, None, None, 'Muslim'),
 (None, None, None, None)]
Run Code Online (Sandbox Code Playgroud)

现在,如果我正确理解您的排序要求,则应执行以下操作:

In [27]: sorted(comb, key=lambda x:sum(v is not None for v in x))
Out[27]: 
[(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')]
Run Code Online (Sandbox Code Playgroud)

我已经习惯None了你使用的地方*,但使用后者是微不足道的.

当然有30个属性你正在看〜10亿个组合,所以列表的扁平化以及随后的排序可能不起作用.但是,对于10亿条目,你还能做些什么呢?