简体   繁体   中英

Find the index of top most element common in two lists

Say, I have two lists

  retrieved = ["foo", "bar", "baz", "foobar"]
  relevant = [ "foobar", "baz"]

What the pythonic way to find the first element present in retrieved that is also "relevant"

So in the example above.. since "baz" is the first relevant object retrieved. It should return 2, corresponding to the index 2 in retrieved.

Thanks

As a for loop

for i, item in enumerate(retrieved):
    if item in relevant:
        print(i)
        break

As a generator

print(next(i for i, item in enumerate(retrieved) if item in relevant))

Read more on enumerate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM