Search For Multiple Elements In Same Sublist Of List
Solution 1:
for sublist indata:
if search1 in sublist and search2 in sublist:
print("there", sublist)
break
Your problem was that in your code, you are searching for the first value, then searching for the second value, separately. You need to search to make sure both are in the same sublist, otherwise you'll get all sublists with either of those values.
The break
statement makes sure the sublist is only printed once.
Update:
To answer your comment, yes there is and it is actually much lighter than the code above. Here it is:
data = [[4,3],[4,7], [6,3], [9,2]]
search = [4,3]
if search in data:
print'yes',search
First, you only need one search variable, search
, set to a list of the search values you are looking for.
Second, we no longer need a for loop because we are no longer looking for individual numbers in a sublist, we are simply looking for item in list
.
The other benefit of this, is that now you can update your search variable by list slicing, adding new search values, or removing some, and also maintaining the order you're looking for. Before, you would have to add new search variables AND add those to the if statement.
Solution 2:
There are some better ways of doing this (you may want to look up the 'key' argument of the sort method on lists), the problem with the code you posted is at line 7: print("there", sublist)
. You should only print once both checks pass, but that line comes after the first check and before the second. I recommend removing that line and combining your nested if into a single if statement using an and
.
Solution 3:
You need to remove the first 'there' print:
for sublist in data:if search1 in sublist:if search2 in sublist:print("there",sublist)found=True
By the description of the problem, I think you should also remove the first 'if(found==False):' section, otherwise you'll end up with multiple prints of 'not there' and the data. In this example - 4 prints (3 redundant).
Solution 4:
This returns matching data items:
>>> data = [[4,3],[4,7], [6,3], [9,2]]
>>> search = [3, 4]
>>> [i for i in data if all(k in i for k in search)]
[[4, 3]]
BTW, the idiomatic way to write "found==False" is "not found".
Post a Comment for "Search For Multiple Elements In Same Sublist Of List"