繁体   English   中英

在列表中查找需要前一个元素的满足条件的元素

[英]find elements in list that fullfill condition WHICH needs the previous element

所以我想测试一个列表是否包含一个元素,该元素满足需要前一个元素的条件。 例如:

liste = [1,3,5,2,6,4,7,1,3,5,2,3,4,7]

现在我想测试两个数字是否在列表中连续出现(例如find(liste, 3, 4)如果 3 直接出现在数组列表中的 4 之前,则find(liste, 3, 4)将给出 TRUE,否则为 FALSE)

给我带来的问题是一个数字在数组中多次出现。 我需要在每次出现时测试它。 有任何想法吗?

仅供参考:我已经在 javascript 中实现了它,但现在想要它在 python 中。 在javascript中我使用:

!!liste.find((element, idx) => idx > 0 && liste[idx-1] == 3 && element == 4)

但是我无法将其翻译成 pyhton ......

您可以执行以下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
zip(liste, liste[1:])

将为您提供每个项目及其前身的成对迭代器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM