Reputation: 131
So I want to test if a list contains a element which fullfills a condition for which the previous element is needed. E.g.:
liste = [1,3,5,2,6,4,7,1,3,5,2,3,4,7]
And now I want to test for two numbers if they occur consecutive in the list (e.g. find(liste, 3, 4)
would give out TRUE if 3 comes directly before 4 in the array liste, otherwise FALSE)
What gives me problems is that a number occurs multiple times in the array. And I need to test it for every occurence. Any ideas?
FYI: I have implemented it in javascript but now want it in python. In javascript I use:
!!liste.find((element, idx) => idx > 0 && liste[idx-1] == 3 && element == 4)
But I have trouble translating that into pyhton...
Upvotes: 1
Views: 92
Reputation: 42207
zip(liste, liste[1:])
will give you a pairwise iterator on every item and its predecessor.
Upvotes: 0
Reputation: 61910
You could do the following zip + any:
liste = [1, 3, 5, 2, 6, 4, 7, 1, 3, 5, 2, 3, 4, 7]
def find(lst, first, second):
return any((first, second) == pair for pair in zip(lst, lst[1:]))
print(find(liste, 3, 4))
Output
True
Upvotes: 2