Compare position and elements of 3 different lists

matilarab :

I'm trying to compare the position and elements of 3 different lists, to then save them in a new list, if at least 2 of the elements at the same position matched.

For Example:

a = [FF2, FF6, FC4]
b = [FB5, FB3, FC4]
c = [FF2, FB3, FM8]

Result = [FF2, FB3, FC4]

At the beginning I used the following code to compare 2 lists, and tried to adapt it for 3 lists, by adding an extra for loop after the for i1 and also adding an or to my if, but went horribly wrong (almost 10 times more values as expected as output).

for i, v in enumerate(a):
    for i1, v1 in enumerate(b):
        if (i==i1) & (v==v1):
            Result.append(v)

This is my current approach, it's working fine, but I have no idea how can I append the matched value to my Result list.

Result = list(x for x, (xa, xb, xc) in enumerate(zip(a, b, c))
     if xa == xb or xb == xc or xa == xc)
rdas :
al = ['FF2', 'FF6', 'FC4']
bl = ['FB5', 'FB3', 'FC4']
cl = ['FF2', 'FB3', 'FM8']

res = []
for a,b,c in zip(al, bl, cl):
    if a == b or b == c or c == a:
        if a == b:
            res.append(a)
        elif b == c:
            res.append(b)
        elif c == a:
            res.append(c)

print(res)

You can iterate through the 3 lists at the same time & append to the resulting list. Use zip()

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=4015&siteId=1