以相反的方式创建 2 个项目集的组合

Combination of 2 itemsets is created in the other way around

我是 Python 的新手,我正在编写代码来组合项目。所以我有这个数组

[1, 12, 13, 15, 21, 24,28, 29, 35, 36]

我正在以这种方式生成我的项目集:

for e1, e2 in combinations(array, 2):
    item = e1| e2 # union of two sets

所以我得到

[1,12] [1,13] [1,15] [1,21]

然后

[24,1]

而不是

[1,24]

然后

[1,28]

这个组合很正常。在所有迭代中我都遇到了这个问题,你知道为什么会这样吗。

如有任何帮助,我们将不胜感激。

我很确定您的困惑是由以下原因引起的:

>>> {1, 12}
{1, 12}
>>> {1, 13}
{1, 13}
# ...
>>> {1, 21}
{1, 21}
>>> {1, 24}
{24, 1}  # first odd example

好吧,集合本质上是无序的,所以 {1, 24}{24, 1} 只是同一事物的两种表示形式。

正如@schwobaseggl 所说,集合是无序的,如果您希望它有序,您应该使用 sorted(item)list(item)