vellattukudy
vellattukudy

Reputation: 789

Compare two python lists and look for conatains

listA = ['ab', 'bv', 'cd']
listB = ['ab_cd', 'AB_vd', 'ab_ud', 'bV_db', 'bv_de', 'cd_scd']

and I have a if condition like

for x in listA :
  if x in listB:
    print "Have"
  else:
    print "dun have"

But it is always looking for the exact values, but what i need to achieve is a conatains type of search in the list. (Ex: ab actually in listB ('ab_cd', 'AB_vd', 'ab_ud'). Any idea guys? Thanks in advance

Upvotes: 0

Views: 46

Answers (3)

Suvasish Sarker
Suvasish Sarker

Reputation: 435

This might help...

 for x in listA:
   for y in listB:
     if x.lower() in y.lower():
       print("Have " + x + " in " + y)

OUTPUT

Have ab in ab_cd

Have ab in AB_vd

Have ab in ab_ud

Have bv in bV_db

Have bv in bv_de

Have cd in ab_cd

Have cd in cd_scd

Upvotes: 1

Prune
Prune

Reputation: 77847

You can save some hassle with the any function. It returns True if any element of the argument iterable is True, False otherwise. The and version of this is called all.

listA = ['ab', 'bv', 'cd', 'qsz']
listB = ['ab_CD', 'AB_vd', 'ab_ud', 'bV_db', 'bv_de', 'CD_SCD']

for want in listA:
if any(want.lower() in target.lower() for target in listB):
        print "Have", want, "in some listB item"
    else:
        print want, "... we don' got dat one"

Output:

Have ab in some listB item
Have bv in some listB item
Have cd in some listB item
qsz ... we don' got dat one

Upvotes: 2

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17132

You can do this:

l = ["ListB does have {}".format(a)
      for a in listA for b in listB if a.lower() in b.lower()]

for el in l:
    print el

Output:

ListB does have ab # 'ab_cd'
ListB does have ab # 'AB_vd'
ListB does have ab # 'ab_ud'
ListB does have bv # 'bV_db'
ListB does have bv # 'bv_de'
ListB does have cd # 'ab_cd'
ListB does have cd # 'cd_scd'

Notice the use of .lower() so as to match all possible combinations. (aA-Aa-AA-aa)

Upvotes: 3

Related Questions