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]
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
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.
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')]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.