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/

相关文章:

algorithm - 为什么客户端计算机不通过 Internet 向其他客户端提供信息以减少服务器带宽?

Python用子串排序字符串数组

python - 解析文件中包含特定文本的行,然后确定下一步的逻辑

python - 为 pyspark 运行 nosetests

python3.6 : KeyError: 'formatters'

python - 有没有一种简单的方法可以使列表表现为文件(使用 ftplib)

algorithm - 计算两个列表之间的相似度

algorithm - 主定理案例

arrays - 将元素从一个数组传递到另一个数组,生成 CSV

令人头疼的 Javascript 数组排序