以下情况如何:
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 亿个条目做什么有用的事情?