Home > Enterprise >  Check if portion of string in a list exists in another list
Check if portion of string in a list exists in another list

Time:06-22

I have the following lists below:

x1 = ['Apples:Red',
      'Apples:Green',
      'Bananas:Yellow',
      'Grapes:Purple',
      'Grapes:Green']
x2 = ['Green', 'Yellow']

I would like to check if the substring after the colon in list x1 matches with the any of the strings in x2.

Looking for an output like this:

['Apples:Green',
 'Bananas:Yellow',
 'Grapes:Green']

CodePudding user response:

You can do something like this (rhs = right-hand side):

x1 = ['Apples:Red', 'Apples:Green', 'Bananas:Yellow', 'Grapes:Purple', 'Grapes:Green']

x2 = ['Green', 'Yellow']


list_new = []
for substring in x1:
    rhs = substring.split(":")[1]
    if rhs in x2:
        list_new.append(substring)

>>> list_new
['Apples:Green', 'Bananas:Yellow', 'Grapes:Green']

CodePudding user response:

If x2 is in any way significant, turn it into a set before doing lookups:

s2 = set(x2)

A list comprehension should do the rest:

[x for x in x1 if x.split(':', 1)[-1] in s2]

Passing maxsplit=1 to str.split ensures that only the first : results in a split.

  • Related