Gius
Gius

Reputation: 514

Compare two list and get first value after condition is satisfied

I have two list with some values in common:

a = [200.04, 300.87, 400.19, 500.67, 600.86, 700.19, 800.48]
b = [200.04, 600.86]

How can I compare the two list to get the first element in list a after the same element in list b? Expected output would be:

c = [300.87, 700.19]

Thank you!

Upvotes: 0

Views: 108

Answers (5)

Mark
Mark

Reputation: 92440

I would zip the list with itself and return the second part of the tuple when the first part is in b:

a = [200.04, 300.87, 400.19, 500.67, 600.86, 700.19, 800.48]
b = [200.04, 600.86]

[n for m, n in zip(a, a[1:]) if m in b]
# [300.87, 700.19]

This is potentially inefficient if b is large, but handles edge cases well — such as different orders or the final item from a being part of b.

Upvotes: 2

kederrac
kederrac

Reputation: 17322

you could use a list comprehension with list.index:

[a[a[:-1].index(e) + 1] for e in b]

output:

[300.87, 700.19]

to avoid so many slicing:

s = a[:-1]
[a[s.index(e) + 1] for e in b]

Upvotes: 1

Erich
Erich

Reputation: 1848

You can just iterate through your input list a and append the successors to list c whenever the item is element of list b.

a = [200.04, 300.87, 400.19, 500.67, 600.86, 700.19, 800.48]
b = [200.04, 600.86]

c = []
for index, item in enumerate(a):
    if item in b and index < len(a) - 1:
        c.append(a[index+1])

This checks the index not to extend bounds, so whenever there is no successor, the list is left unchanged.

Upvotes: 1

Nick
Nick

Reputation: 147196

Here's a verbose way of doing this, which checks that the value in b actually exists in a so as to avoid errors if it doesn't:

a = [200.04, 300.87, 400.19, 500.67, 600.86, 700.19, 800.48]
b = [200.04, 600.86]
c = []
for v in b:
    try:
        i = a.index(v)
    except ValueError:
        i = -1
    if i >= 0 and i < len(a) - 1:
        c.append(a[i+1])
    else:
        c.append(float('nan'))

print(c)

Output:

[300.87, 700.19]

Upvotes: 1

WangGang
WangGang

Reputation: 533

You can use index positions to solve this.

a = [200.04, 300.87, 400.19, 500.67, 600.86, 700.19, 800.48]
b = [200.04, 600.86]
c = []
for x in b:
    c.append(a[a.index(x)+1])

If you run this program, then c = [300.87, 700.19]

Upvotes: 1

Related Questions