Reputation: 1127
I have a list of lists:
a = [[1, 2], [2, 3], [4, 3]]
How to get the following effect in two steps ?:
b = [[1, 2, 2, 3], [1, 2, 4, 3], [2, 3, 4, 3]]
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
Reputation: 402553
timegb is right. An elegant solution involves some amount of trickery and deception. I'll try and break down the steps.
itertools.combinations
map
and chain
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