Home > database >  flattening an iterable by removing one element at a time
flattening an iterable by removing one element at a time

Time:08-24

I have a list of tuples such as:

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

I'd like to flatten it out in a loop, but without one of the elements in every loop.

The expected result should be:

[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

To flatten it out, I could use:

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

But I need to find how to get this my_iterable

CodePudding user response:

You may just use list slicing.

from itertools import chain

bins = [(0, 1500), (0, 1500), (2000, 40000)]
for i in range(len(bins)):
    my_iterable = bins[:i]   bins[i 1:]
    print(list(chain.from_iterable(my_iterable)))

CodePudding user response:

I hope I've understood your question right, but you can use 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)))

Prints:

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

CodePudding user response:

You can use the itertools.combinations, but its culling order is opposite to what you want, so you have to reverse it twice:

>>> from itertools import chain, combinations
>>> for tpl in combinations(reversed(lst), len(lst) - 1):
...     print(list(chain.from_iterable(reversed(tpl))))
...
[0, 1500, 2000, 40000]
[0, 1500, 2000, 40000]
[0, 1500, 0, 1500]
  • Related