检查列表中是否有两个项目按特定顺序排列? [英] Check if two items are in a list, in a particular order?

查看:47
本文介绍了检查列表中是否有两个项目按特定顺序排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个列表v = [1, 2, 3, 4, 3, 1, 2].我想编写一个函数find_pair,它将检查列表中是否有两个数字并且彼此相邻.因此,find_pair(v, 2, 3)应该返回True,但是find_pair(v, 1, 4)应该返回False.

Say I have a list v = [1, 2, 3, 4, 3, 1, 2]. I want to write a function, find_pair which will check if two numbers are in the list and adjacent to each other. So, find_pair(v, 2, 3) should return True, but find_pair(v, 1, 4) should return False.

是否可以不循环地实现find_pair?

Is it possible to implement find_pair without a loop?

推荐答案

v = [1,2,3,4,3,1,2]
any([2,3] == v[i:i+2] for i in xrange(len(v) - 1))

虽然@PaoloCapriotti的版本可以解决问题,但此方法更快,因为一旦找到匹配项,它将停止解析v.

While @PaoloCapriotti's version does the trick, this one is faster, because it stops parsing the v as soon as a match is found.

这篇关于检查列表中是否有两个项目按特定顺序排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆