首页 > 解决方案 > find elements in list that fullfill condition WHICH needs the previous element

问题描述

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...

标签: pythonlist

解决方案


您可以执行以下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))

输出

True

推荐阅读