Tomasz Przemski
Tomasz Przemski

Reputation: 1127

Operations on sub-lists in list

I have a list of lists:

a = [[1, 2], [2, 3], [4, 3]]

How to get the following effect in two steps ?:

  1. b = [[1, 2, 2, 3], [1, 2, 4, 3], [2, 3, 4, 3]]
  2. b = [[1, 2, 3], [1, 2, 4, 3]], it means:

    1.1. If the same values occur in the sub-list b[i] next to each other, then one of these values must be deleted.

    2.2. If the same values appear in a given sub-list b[i] but not next to each other, then the entire sub-list b[i] must be deleted.

Upvotes: 0

Views: 102

Answers (1)

cs95
cs95

Reputation: 402553

timegb is right. An elegant solution involves some amount of trickery and deception. I'll try and break down the steps.

  • find all 2-combinations of your input using itertools.combinations
  • flatten returned combinations with map and chain
  • for each combination, group by consecutive elements
  • keep only those that satisfy your condition by doing a length check.
from itertools import chain, combinations, groupby

out = []
for r in map(lambda x: list(chain.from_iterable(x)), combinations(a, 2)):
     j = [i for i, _ in groupby(r)]
     if len(j) <= len(set(r)):
         out.append(j)
print(out)
[[1, 2, 3], [1, 2, 4, 3]]

If you need only the first part, just find combinations and flatten:

out = list(map(lambda x: list(chain.from_iterable(x)), combinations(a, 2)))

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

Upvotes: 1

Related Questions