尝试查看列表中的数字与其邻居的距离是否在1以内



我试图比较这个列表中的所有数字,如果它们中的任何一个在列表中靠近它们的数字的1以内,如果是这样,那么我想要命令打印True。我意识到,通过对列表中的最后一项应用[x+1],我将超出列表的范围。我试图避免这种情况,但我仍然得到相同的错误。任何帮助都会很感激。谢谢:)

listed = [2,4,5,7]
for x in listed[:-1]:
if listed[x+1] - listed[x] == 1:
print(True)
else:
print(False)
IndexError                                Traceback (most recent call last)
Input In [155], in <cell line: 3>()
1 listed = [2,4,5,7]
3 for x in listed[:-1]:
----> 4         if listed[x+1] - listed[x] == 1:
5             print(True)
6         else:
IndexError: list index out of range

itertools.pairwise为您提供了可以使用的列表中的漂亮相邻对:

from itertools import pairwise
vals = [x for x in pairwise(listed) if abs(x[0] - x[1]) <= 1]
print(vals)

输出:

[(4, 5)]

最新更新