iam.Carrot
iam.Carrot

Reputation: 5286

Get a tuple from a list of tuple if the element occurs in a list of string

Hi I am working on a data transforming project. I have a List of tuples:

A = [("someThing",0),("someThingOnce",1),("someThingTwice",2)]

and an another list of string:

B = ["something","somethingonce","somethingagain"]

Now what I want to do is, I want the elements from list A that are present in list B.

The desired output is:

C = [("someThing",0),("someThingOnce",1)]

How can I achieve this in an optimised way since, list B has 7000 elements while list A has at max 20 elements.

I can't use numpy as the lists aren't of the same type, i..e B might contain numbers as well.

The tuple[0] in list A elements might repeat as well.

Upvotes: 2

Views: 61

Answers (1)

Joe Iddon
Joe Iddon

Reputation: 20424

A list-comprehension is the most efficient solution for this (if A has less elements than B).

>>> A = [("someThing",0),("someThingOnce",1),("someThingTwice",2)]
>>> B = ["something","somethingonce","somethingagain"]
>>> C = [(i, j) for i, j in A if i.lower() in B]
>>> C
[('someThing', 0), ('someThingOnce', 1)]

Upvotes: 1

Related Questions