如何在python字典中选择附近的键?

2024-09-28 05:27:38 发布

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

请考虑下面的Python代码:

def allot():
    dict2 = {'1': 1, '2': 1, '3': 0, '4': , '5': 1}
    allotted_id = None

    for k in dict2:
        usr_id = 3
        if (str(usr_id) != k):
            continue;

        if ((str(usr_id) == k) and (dict2[str(usr_id)] == 1)):

            print("\n user Requested Id : ", usr_id)
            print("\n user Requested Id is available ! ")
            allotted_id = k
            break;
        else:
            print("\n user Requested Id : ", usr_id)
            print("\n user Requested Id is not available ! ")
            usr_id = usr_id + 1
            if (dict2[str(usr_id)] == 1):
                allotted_id = usr_id
                break;

    print('So allotted dict2 Id', allotted_id)

allot()

的“dict2”if values == 1 then it is active or if values == 0中,它处于非活动状态。在这里,将usr_iddict2中的键id匹配

案例1:dict2 = {'1': 1, '2': 1, '3': 1, '4': 1, '5': 1}。现在usr_id==3,dict2键'3'==1。如此分配id=3

案例2:dict2 = {'1': 1, '2': 1, '3': 0, '4': 1, '5': 1}。现在usr_id==3和dict2键“3”==0。然后分配下一个活动id。所以分配的id=4

案例3:dict2 = {'1': 1, '2': 1, '3': 0, '4': 0, '5': 1}。现在usr_id==3和dict2键'3'&;'4'==0 . 因此,距离usr_id要分配的下一个最近的活动id(只不过是键id“2”)。如何操作

为我的案例3场景提供指导。提前谢谢


Tags: idifisusr案例availableprintbreak
3条回答

我会使用numpy:

user_ids = np.array(range(5))
valid_user = np.array([1, 1, 0, 0, 1])
anchor_id = 2

dist_from_anchor = np.abs(user_ids - anchor_id)
dist_from_anchor[valid_user == 0] = len(user_ids) +1 #will not be the min
print(np.argmin(dist_from_anchor))

我使用的最小用户id为0(只是一个cs的东西…),但您可以很容易地将其更改为1

假设您不希望对代码进行效率更改,那么您将覆盖for k in dict2循环中的usr\u id

def allot():
    dict2 = {'1': 1, '2': 1, '3': 0, '4': , '5': 1}
    allotted_id = None

    usr_id = 3  # Move this out of the loop

    for k in dict2:       
        if (str(usr_id) != k):
            continue;

        if ((str(usr_id) == k) and (dict2[str(usr_id)] == 1)):

            print("\n user Requested Id : ", usr_id)
            print("\n user Requested Id is available ! ")
            allotted_id = k
            break;
        else:
            print("\n user Requested Id : ", usr_id)
            print("\n user Requested Id is not available ! ")
            usr_id = usr_id + 1
            if (dict2[str(usr_id)] == 1):
                allotted_id = usr_id
                break;

    print('So allotted dict2 Id', allotted_id)

allot()

您可以编写此代码来执行更多检查,并更多地使用字典结构

def allot():
    # Variables to Enter
    dict2 = {1: 1, 2: 1, 3: 0, 4: 0, 5: 1}
    usr_id = 3

    # Boolean Variables
    allotted_id = None
    upper_exhausted = False
    lower_exhausted = False

    # Need to calculate the min and max to know when to stop searching
    max_id = max(dict2.keys())
    min_id = min(dict2.keys())

    # Check the initial ID
    if dict2[usr_id] == 0:
        print("ID {} inactive. Continuing search.".format(usr_id))
    else:
        allotted_id = usr_id

    # Run two searches - one increasing through the dictionary 
    # and one decreasing through the dictionary
    upper_usr_id = usr_id + 1
    lower_usr_id = usr_id - 1

    # Run loop whilst the max and min dict key haven't been reached 
    # AND there's no allotted ID.
    while not allotted_id:
        if not upper_exhausted:
            if dict2[upper_usr_id] == 0:
                print("ID {} inactive. Continuing search.".format(upper_usr_id))
                if upper_usr_id < max_id:
                    upper_usr_id += 1
                else:
                    upper_exhausted = True  # Maximum has been reached
            else:
                allotted_id = upper_usr_id
        if not lower_exhausted:
            if dict2[lower_usr_id] == 0:
                print("ID {} inactive. Continuing search.".format(lower_usr_id))
                if lower_usr_id > min_id:
                    lower_usr_id -= 1
                else:
                    lower_exhausted = True  # Minimum has been reached
            else:
                allotted_id = lower_usr_id

        # Exhausted all values - No Data value
        if upper_exhausted and lower_exhausted:
            allotted_id = -999

    if allotted_id == -999:
        print("Couldn't allot an ID")
    else:
        print("Allotted ID is: {}".format(allotted_id))

allot()

我建议采用不同的方法(不知道你的方法有多灵活)——

像这样存储数据

dict2 = {"1": {1, 2, 5}, "0": {3, 4}} # 1 for available Ids and 0 for allocated

现在,对于任何传入的用户id

if usr_id in dict2["1"]:
    allotted_id = usr_id
elif usr_id in dict2["0"]:
    # either return the first available Or
    # traverse and return the next higher user id available 
else:
    # exception

相关问题 更多 >

    热门问题