Ad

Element Comparison Using List Comprehension And Conditions

I have two lists in the form:

a = [[x1, 1], [x2, 0], [x3, 4], [x4, 12], [x5, 15]]

b = [[x2, 10], [x3, 41], [x7, 50]]

I thought I could do something like below to get the ids x1, x2, x3 and so on..

x = [item for item in b if item in a]

print(x)
[[x2, 10], [x3, 41]]

I actually want to print the elements in b that are in a and compare their values

[x2, 10] -> [x2, 0]
[x3, 41] -> [x3, 4]

so in the example above only print elements from a if b[0][1] == 0 & a[1][1] != 0

Any help would be most appreciated!

Ad

Answer

you can use:

a = [['x1', 1], ['x2', 0], ['x3', 4], ['x4', 12], ['x5', 15]]

b = [['x2', 10], ['x3', 41], ['x7', 50]]

a_dict = dict(a)

print('    b           a')
for x, val in b:
    if x in a_dict:
        print(f'[{x}, {val}] --> [{x}, {a_dict[x]}]')

output:

    b           a
[x2, 10] --> [x2, 0]
[x3, 41] --> [x3, 4]
Ad
source: stackoverflow.com
Ad