Home > Net >  way to check two lists positions and group them
way to check two lists positions and group them

Time:11-20

I have 2 lists:

a1 = [1, 4, 5, 3, 6, 2]
b1 = [5, 3, 2, 4, 6, 1]

i want now do it with positions: like: if a1 pos == b1 pos:

group1 = [6]

if pair 4 - 3 and 3 - 4:

group2 = [3, 4]

if pair [1, 5] and [5, 2] and [2, 1]

group3 = [1, 2, 5]

CodePudding user response:

You can do:

groups = {}
for a, b in zip(a1, b1):
    group = groups.get(a, {a}) | groups.get(b, {b})
    for x in group:
        groups[x] = group

groups = set(map(tuple, groups.values()))
# {(6,), (3, 4), (1, 2, 5)}

This iterates the two lists pairwise (zip) and keeps track of the permutation group for each element using set union (|). It then reduces it to the unique groups (using a set of tuple as the original sets values are not hashable)

CodePudding user response:

Not exactly sure what you mean by your latter 2 cases, and what their inputs would look like, but for the first case you can do:

z = [x for x, y in zip(a1, b1) if x == y]
  • Related