I have two lists l1
and l2
contains elements like
l1 = ['a','b','c','d']
l2 = ['a is greater', 'f is greater', 'c is greater']
I want to compare elements of l1 and finds if l2 contains in their element or not. The desire output would be
f is greater
Following the code I tried,
for i in l2:
for j in l2:
if j not in l1:
print(i)
but what my observed output is
a is greater
a is greater
f is greater
f is greater
c is greater
c is greater
Please help me out to know what I need to add to get the appropriate output. Thanks.
CodePudding user response:
Use:
l1 = ['a','b','c','d']
l2 = ['a is greater', 'f is greater', 'c is greater']
# iterate over the elements of l2
for i in l2:
# check if the first letter of e is in l1
if i[0] not in l1:
print(i)
Output
f is greater
You don't need to iterate twice over the elements of l2
, and to check if if a value (i[0]
) is in a collection (l1
) use in
.
UPDATE
If you want to check a different position just change the index on i, for example, if you wan to check the last position do:
l1 = ['a','b','c','d']
l2 = ['Greater is c', 'Greater is f', 'Greater is d']
# iterate over the elements of l2
for i in l2:
# check if the first letter of e is in l1
if i[-1] not in l1: # note the -1
print(i)
Output
Greater is f
If you want consider where all words (delimited by spaces) of a sentencer are not present in l1
, one approach:
l1 = ['a', 'b', 'c', 'd']
l2 = ['Greater is c', 'Greater is f', 'f is greater', "Hello a cat"]
s1 = set(l1)
# iterate over the elements of l2
for i in l2:
# check if the first letter of e is in l1
if s1.isdisjoint(i.split()):
print(i)
Output
Greater is f
f is greater
If checking for string containment, do:
l1 = ['Book Date:', 'Statement Number:', 'Opening Book Balance:', 'Closing Book Balance:', 'Number Of Debits:',
'Number of Credits:', 'Total Debits:', 'Total Credits:', 'Report Date:', 'Created by:', 'Modified by:', 'Printed by:']
l2 = ['<p>Book Date: 06-01-21 To 06-30-21</p>', '<p>Statement Number: 126 </p>', '<p>this value need to print</p>']
# iterate over the elements of l2
for i in l2:
# check if the first letter of e is in l1
if not any(j in i for j in l1):
print(i)
Output
<p>this value need to print</p>
CodePudding user response:
Here you go:
ref = ('a','b','c','d')
l2 = ['a is greater', 'f is greater', 'c is greater']
l3 = ['Greater is c', 'Greater is f', 'Greater is d']
l4 = ['...c...', '...f...', '...d...']
[item for item in l2 if not item.startswith(ref)] # 'f is greater'
[item for item in l3 if not item.endswith(ref)] # 'Greater is f'
[item for item in l4 if not any(letter in item for letter in ref)] # '...f...'