为什么 itertools.combinations 会在输出中添加额外的逗号以及如何避免它?

Why does itertools.combinations add extra commas to the ouput and how to avoid it?

我希望列表中所有可能的长度组合最多为 2 个项目。我想要它作为一行,我知道如何在更多行中进行。当我尝试这个时:

mylist=[1, 2, 3, 4]
[x for l in range(1,3) for x in itertools.combinations(mylist, l)]

我得到的结果是在长度为 1 的组合后附加了逗号。

[(1,), (2,), (3,), (4,), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

不太明白他们是从哪里来的。当然,我可以直接删除它们,但这对我来说似乎不对,我敢肯定必须有另一种方法来生成此列表而无需额外的逗号。这就是我想要的:

[(1), (2), (3), (4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

因为如果没有逗号,单值元组就不能成为元组:

>>> (1,)
(1,)
>>> (1)
1
>>> 

所以你想要的是不可能的

但是您可以像这样将单值元组转换为整数:

print([x if len(x) > 1 else x[0] for l in range(1,3) for x in itertools.combinations(mylist, l)])

输出:

[1, 2, 3, 4, (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

您只想使用 tuple 吗?这是因为一个元素tuple,用list不好吗?如下所示:

mylist=[1, 2, 3, 4]
[list(x) for l in range(1,3) for x in itertools.combinations(mylist, l)]

输出:

[[1], [2], [3], [4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
itertools.combinations

returns 一个元组。 引用自 docs:

Return r length subsequences of elements from the input iterable. If you notice the equivalent code, you can see that

yield tuple(pool[i] for i in indices)

正在生成元组。

如果元组中只有一个元素,则必须有一个逗号来告诉 python 它是一个元组。 例如:

>>> ('a')
'a'
>>> ('a',)
('a',)

你实际上可以把它转换成一个列表:

[list(x) for l in range(1,3) for x in itertools.combinations(mylist, l)]