次はどうですか:
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)]
さて、私があなたのソート要件を正しく理解していれば、以下はそれを行うべきです:
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')]
私はあなたが使用None
した場所を使用しまし*
たが、後者を使用するのは簡単です。
もちろん、30の属性では、最大10億の組み合わせを見ているので、リストのフラット化とその後の並べ替えはおそらく機能しません。しかし、とにかく10億のエントリで何が有効にできるでしょうか。