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

问题描述 投票:0回答:3

请考虑以下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场景提供指导。预先感谢。

python
3个回答
0
投票

我建议使用其他方法(不知道您的方法有多灵活)-

像这样存储您的数据

dict2 = {"1": [1, 2, 3, 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 the list 
    # and return the next higher user id available 
else:
    # exception

0
投票

我将使用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))

我使用最小的user_id作为0(只是一个cs ...),但是您可以轻松地将其更改为1 ...


0
投票

假设您不希望对代码进行任何效率更改,那么您将覆盖for k in dict2循环中的usr_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()

目前,代码在您选择的用户ID之前不会考虑用户ID。有很多更有效的方法可以做到,其中一种可能是:

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

    original_id = usr_id
    while not allotted_id:
        if looped and usr_id == original_id:
            allotted_id = -999  # No Data Value
        else:
            if dict2[usr_id] == 0:
                print("ID {} inactive. Continuing search.".format(usr_id))
                if usr_id != max(dict2.keys()):  # Stops increasing at end of dict
                    usr_id += 1
                else:
                    usr_id = min(dict2.keys())
                    looped = True  # Set variable to break endless loop
            else:
                allotted_id = usr_id

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

allot()
© www.soinside.com 2019 - 2024. All rights reserved.