【问题标题】:flattening an iterable by removing one element at a time通过一次删除一个元素来展平迭代
【发布时间】:2022-08-23 20:32:31
【问题描述】:

我有一个元组列表,例如:

bins = [(0, 1500), (0, 1500), (2000, 40000)]

我想在一个循环中将其展平,但每个循环中都没有一个元素。

预期的结果应该是:

[0, 1500, 2000, 40000]  # first loop, first element is not there
[0, 1500, 2000, 40000]  # second loop, second element is not there
[0, 1500, 0, 1500]  # third loop, last element is not there

为了展平它,我可以使用:

from itertools import chain
list(chain.from_iterable(my_iterable))

但我需要找到如何得到这个my_iterable

    标签: python loops iterable


    【解决方案1】:

    我希望我正确理解了您的问题,但您可以使用itertools.combinations

    from itertools import combinations, chain
    
    bins = [(0, 1500), (0, 1500), (2000, 40000)]
    
    for c in combinations(bins, len(bins) - 1):
        print(list(chain.from_iterable(c)))
    

    印刷:

    [0, 1500, 0, 1500]
    [0, 1500, 2000, 40000]
    [0, 1500, 2000, 40000]
    

    【讨论】:

      猜你喜欢
      • 2011-08-15
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多