Reputation: 1
I need to compare elements from individual list of lists. For example here are my two list:
listing = [['tl.48', 'tl.49', 'tl.57'], ['tl.23', 'tl.45', 'tl.12']];
search = [['tl.48','tl.57']];
Now my goal is to look for each item in search into each item in listing and if the two items 'tl.48'
, 'tl.57'
matches the items in listing then I choose that item from the listing and append it in an empty list. listing[0]
has a size of 3 elements and search[0][0]
and search[0][1]
are present at listing[0][0]
and listing[0][2]
. How can I get listing[0]
in a separate list and append it. If listing[0]
is of size 4 and search[0][0]
and search[0][1]
are present in listing[0]
, I will still add listing[0]
to the new list. How can I do it?
Thanks.
Upvotes: 0
Views: 229
Reputation: 7952
[lst for lst in listing if all([True if term in lst else False for term in search[0]])]
Result: [['tl.48', 'tl.49', 'tl.57']]
This, for each list
in listing
, checks if each search term is in
the list
, only appending it if all
such terms are there.
Note: search is a list containing a single list, which is why we use search[0]
. If it's just the list of elements, use search
instead.
Roughly equivalent to (same result, different method):
result = []
for lst in listing:
valid = True
for term in search[0]:
if term not in lst:
valid = False
if valid:
result.append(lst)
If this is going to be true list comparisons (where search
and listing
are both lists of lists), you'll need to find a more robust solution.
Upvotes: 1