【问题标题】:Why does itertools.combinations add extra commas to the ouput and how to avoid it?为什么 itertools.combinations 会在输出中添加额外的逗号以及如何避免它?
【发布时间】:2021-08-20 09:49:42
【问题描述】:

我希望列表中所有可能的长度组合最多为 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,) 表示它们是一个元组
  • 我当然可以删除它们 - 具体如何?

标签: python combinations itertools


【解决方案1】:

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

>>> (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)]

【讨论】:

    【解决方案2】:

    您只想使用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]]
    

    【讨论】:

    • 是的,既然您提到了,我实际上更喜欢将它们作为列表。谢谢!
    【解决方案3】:
    itertools.combinations
    

    返回一个元组。 引用自docs:

    从输入迭代中返回 r 个长度的元素子序列。 如果您注意到等效代码,您可以看到

    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)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-13
      • 2011-06-24
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多