如何找出数组是否包含数字3,以及是否有两个3彼此相邻

给定一个整数列表,例如:

lst = [3,3,6,5,8,3,4,5]

然后,我使用列表理解来找出数字3出现在此列表中的索引:

[i for i, x in enumerate(lst) if x == 3]

但是现在我无法弄清楚如何查看数字3是否位于另一个3旁边,并将其返回为True


qq_遁去的一_1
浏览 109回答 3
3回答

动漫人物

您可以使用 zip() 成对循环访问数据:any(a == b == 3 for a, b in zip(lst, lst[1:]))然后进行链式比较,以检查a和b是否都等于3。函数 any() 检查这些更改的比较是否为真。FWIW,另一种循环成对()的方法显示在文档的迭代工具食谱部分。希望这有帮助:-)

波斯汪

但是现在我无法弄清楚如何查看数字3是否位于另一个3旁边,并将其返回为True好吧,由于您的结果是可以找到3的所有索引的列表,因此您只需检查任何两个连续的索引,看看它们是否相差1。可悲的是,“窗口化”迭代器仍然不是标准库的一部分,但复制它们很容易:indices = [3,3,6,5,8,3,4,5] for i, j in zip(indices, indices[1:]):     ...

大话西游666

这是另一种非常直接的方法(有点过度使用)def check(index, lst):&nbsp; &nbsp; if index > 0 and lst[index] == lst[index - 1] and lst[index] == 3:&nbsp; &nbsp; &nbsp; &nbsp; return True&nbsp; &nbsp; if index < len(lst) and lst[index] == lst[index + 1] and lst[index] == 3:&nbsp; &nbsp; &nbsp; &nbsp; return True&nbsp; &nbsp; return Falselst = [3,3,6,5,8,3,4,5]for index in range(len(lst)):&nbsp; &nbsp; print(check(index, lst))输出:TrueTrueFalseFalseFalseFalseFalse
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python