Ad

If Statement And Zip

- 1 answer

I have three lists, say:

a = [1, 2, 3, 4, 5]
b = [a, b, c, d, e]

x = [1, 3, 5]

I want to do, with an output like:

for item in x:
    if item in a:
        print(zip(a[x], b))

1a
3c
5e

I am confused with how to print the corresponding item in a and the item from b. Any help would be much appreciated, thanks.

Ad

Answer

a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd', 'e']
x = [1, 3, 5]

for i, j in zip(a, b):
    if i in x:
        print(f"{i}{j}")

or just use list comprehension:

[print (f"{i}{j}") for i, j in zip(a, b) if i in x]

output:

1a
3c
5e

If your lists are longer, though, it might be better to pre-process your data, building a dict mapping values from a to those of b:

d = {k:v for k, v in zip(a, b)}

for k in x:
    print('{}{}'.format(k, d[k]))

# 1a
# 3c
# 5e 
Ad
source: stackoverflow.com
Ad