检查数字是在麻木之后还是之前

2024-10-01 09:30:38 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有四个数字,比如2346,我想检查一下,它们是在一个数字之前还是之后。例如,如果我选择2,那么我希望代码说3就在数字后面;当我选择3时,代码应该输出23之前,而43之后;当我选择4时,代码应该输出3就在4之前。如何在Python中实现这一点? 这就是我迄今为止所尝试的

a = [2,3,4,6]
def check(noToCheck, List):
    if noToCheck in List:
        for elem in List:
            if noToCheck == elem+1:
                print elem+" comes just before "+noToCheck
            elif noToCheck == elem-1:
                print elem+" comes just after "+noToCheck
            else:
                pass

这很管用,但有什么更干净的方法呢


Tags: 代码inforifdefcheck数字list
1条回答
网友
1楼 · 发布于 2024-10-01 09:30:38

这将接收一个名为num(例如5)的值,然后检查它的相邻数字(例如4和6)是否在数组中,如果在数组中,它将打印它们

def getContext(arr,num):
    if (num+1 in arr):
        print str(num+1) + " is after and in the array"        
    if (num-1 in arr):
        print str(num-1) + " is before and in the array"

arr = [2,3,4,6]

getContext(arr,2)

相关问题 更多 >