-1

I want to intersect two list. But the lists are of different types, one is list of tuples and the other is list of integers. As a result I need a final list of tuples.

List 1: [(1.0, 2481), (0.11764705882352941, 2), (0.033, 2), (0.0, 2479), (0.0, 2478), (0.0, 2477)]
List2 : [2481,2, 2477]

Desired results:

[(1.0, 2481), (0.11764705882352941, 2), (0.0, 2477)]

I want to include only one tuple in final list which comes first If you specifically look at this case (0.11764705882352941, 2), (0.033, 2), I only want to include this (0.11764705882352941, 2) tuple into final list.

I can loop through the list of tuples but I am not sure this will be efficient on large lists.

Is there any better way to do it?

Thanks in advance!

Sniper
  • 418
  • 3
  • 12
  • Please go through the [intro tour](https://stackoverflow.com/tour), the [help center](https://stackoverflow.com/help) and [how to ask a good question](https://stackoverflow.com/help/how-to-ask) to see how this site works and to help you improve your current and future questions, which can help you get better answers. You have to make an honest attempt at the solution, and then ask a *specific* question about your implementation. – Prune Apr 03 '21 at 22:15
  • "What is the best way?" is usually a wrapper around "give me code/design to solve this problem" -- which is off-topic for Stack Overflow. – Prune Apr 03 '21 at 22:15
  • `[t for t in list_1 if t[1] in list_2]`? If `list_2` is large and you want to make it more efficient, turn `list_2` into a `set` so that lookups will be O(1). – Samwise Apr 03 '21 at 22:18

1 Answers1

0

Since you may have to traverse the entire list to find the desired element, you do have to got through the list at least once. However, if you're doing this many times on a large list, you could de-duplicate your list and make a reverse dict in one pass.

ref = {right: left for left, right in list1}

Since a dict keeps only the most recent assigned entry, this will give you a dict of all of the integers as keys, and the floats as their values. Now, all you need for your process is a direct O(1) look-up in this dict:

result = [key, dict[key] for key in list2]

Will that do the job for you?

Prune
  • 76,765
  • 14
  • 60
  • 81