I have something like this
lists = [ [1,2,3] , [4,5,6] , [8,9,10] ]
and I would like to be able to search for a element of a list and return the entirety of the list
search = 5
result = [4,5,6]
(doesn't have to be that exact format but I would like to be able to see all the elements from the list)
I've looked at other forums and when they search I only returns a true or false value, so I'm not sure if what I would like to do is even possible
CodePudding user response:
You can abuse the next
function to get the first element of a iterable that matches a predicate like this:
next(i for i in iterable if p(i))
If no element exists this will throw a StopIteration
exception that you can optionally catch.
You can also use the in
operator to find if a element is in a list:
5 in [1,2,3]
# False
5 in [4,5,6]
# True
Combining the two:
next(l for l in lists if 5 in l)
CodePudding user response:
You can use numpy
a = np.array(lists)
out = a[np.where(a==5, True, False).any(1)].tolist()
CodePudding user response:
In this kind of situation, I would create a function that will iterate the list and use the in
operator to see if the value is in the list or not and finally return the index number of that value x or return False.
def result(srch, list):
for x in list:
if srch in x:
return list[list.index(x)]
return False
lists = [[1, 2, 3], [4, 5, 6], [8, 9, 10]]
search = 15
print(result(search, lists))
Result:
[4, 5, 6]