userD1989
userD1989

Reputation: 47

Identify the tuple in the list of tuples if the tuple contains substring

I have a list

l1 = [('is', 'VBZ'), ('plant', 'NN')]

I want to check if the VB in present in the list

I have used the following code but it is not giving me the result.

match = [x for x in l1 if 'VB' in x]

Upvotes: 0

Views: 1870

Answers (3)

Sociopath
Sociopath

Reputation: 13426

I think you need:

l1 = [('is', 'VBZ'), ('plant', 'NN')]

print([x for x in l1 if 'VB' in x[1]])

Output

[('is', 'VBZ')]

Why your code is not working

You are checking if VB is in ('is', 'VBZ') and it is not. As I understand those are POS tags and will always be at 1st index. You need to check if VB is present at index 1 of each tuple in the list

Upvotes: 1

Umesh
Umesh

Reputation: 971

In your solution you want to check for substring, for that you will need to search through the elements in Tuple.

If you want to search exact string then your solution is right

'VBZ' in ('is', 'VBZ')
==> True

'VB' in ('is', 'VBZ')
==> False

if you know exatly 2 elements will be in tuple

[tu for tu in l1 if 'VB' in (tu[1] or tu[0])] 

==> [('is', 'VBZ')]

if you are not sure of the elements in tuple

[tu for tu in l1 if any(['VB' in elem for elem in tu])] 
==> [('is', 'VBZ')]


Upvotes: 1

pnv
pnv

Reputation: 3145

In case you do not have 'VB' occurring always on 1st index,

match = [y for y in l1 if any(['VB' in x for x in y])]

step 1 : Visit a tuple one by one.

step 2 : Check if string 'VB' exists in any of the string-items of the visited tuple.

Upvotes: 0

Related Questions