I have two list of strings
a = ['a','b','c']
b = ['aa','b','d']
I need to check if every element from list a is included in any element in list b
I tried couple of solutions, but below one I thought should work, but it always returning True
def list_compare(list1,list2):
for item in list1:
if any(item for s in list2):
return True
return False
print(list_compare(a,b))
Anyone has any idea ?
I need that comparison for searching keywords in query files. I'm searching if all keywords are in file (file is split into lines as list) and if yes then return all lines containing any of the keyword.
You can use any
and all
like this
>>> def list_compare(list1,list2):
... return all(any(x in y for y in list2) for x in list1)
...
>>> print(list_compare(a,b))
False
def compare(list1,list2):
for item in list1:
if item in list2: #checking the item is present in list2
continue # if yes, goes for next item in list1 to check
else:
return False #if no, immediately comes out with "False"
else:
return True #reaches here, only if all the items in list1 is
#present in list2 , returning "True"
print(compare(lista,listb))
Finds words usage in lines. Word can be a substring of line (line can contain multiple words).
wordsToFind = ['a','b','c']
linesOfDocument = ['aa','ab','1234b','d']
for word in wordsToFind:
for line in linesOfDocument:
if word in line:
print('Found word ' + word + ' in line ' + line)
Output of example:
Found word a in line aa
Found word a in line ab
Found word b in line ab
Found word b in line 1234b
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.