python - 在 python 中进行组合

标签 python algorithm sorting combinations combinatorics

我有四个值(value)观

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

我需要将这些按空值组合排列,例如 -

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

我需要按列表中的维数升序排列。因此具有一个值的组合应该在最前面。我有大约 30 多个属性,所以我需要一种在 Python 中自动执行此操作的方法

有什么想法吗?

最佳答案

以下情况如何:

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 亿个条目做什么?

关于python - 在 python 中进行组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13708253/

相关文章:

python - 可以将矩阵作为 Keras 嵌入层的输入吗?

python - 实现中位数为三的快速排序

sorting - 使用动态改变其行为的比较器对向量进行排序

python - 将文件中的列从高到低排序

python - PostgreSQL ALTER SEQUENCE 在 django 中使用 psycopg2

python - 如何替换python列表特定索引处的值?

python - Django 立即保存并返回对象(使用自定义 pk)

algorithm - 冒泡排序中执行的平均交换次数

c++ - 堆排序 - 哪个堆(最小/最大)用于升序和降序排序?

java - 在 Java 中使用 Bag 的原因