生成一个随机数,避免给定列表中的重复项

2024-06-17 08:11:53 发布

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

我正在做一个项目,我需要写一个函数来为我们公司的每个客户生成ID。已经有一个现有的客户列表,其中一些客户的数字ID为5到6位,范围为40000到200000。还有其他现有客户没有ID,我希望与现有的ID号保持一致(例如43606或125490)

因此,为了保持类似的格式,我创建了一个Exclusion_List,其中包含所有现有的ID号。然后我将使用np.random.uniform(low=40000, high=200000)编写一个函数,以便在该范围内生成一个看起来与其他ID号类似的数字

我的问题是,我不知道如何设置一个循环来检查随机生成的ID是否已经在排除列表中,如果已经在排除列表中;然后生成一个新的

这就是我到目前为止所做的:

exclusions = [43606,125490,...]

def ID_Generator(new_clients): # This is a list of new client

  new_client_IDs = []

  for client in new_clients:

    ID = int(np.random.uniform(low=40000, high=200000))

    while ID not in exclusions:

      new_client_IDs.append(ID)

当随机生成的数字在排除列表中时,我不确定如何处理这种情况。我希望该函数能够输出一个数据帧,在一列中包含客户机名称,在第二列中包含ID号

谢谢你在这方面的帮助


Tags: 函数clientidids列表new客户np
3条回答

我现在能想到的简单方法是

  1. 40000-200000生成一个列表
  2. 从上面的列表中删除所有exclusions
  3. 从剩余列表中随机选择任何id(如果顺序有问题,请按顺序使用id)

import random exclusions = [43606,125490] all = range(40000,200000) remaining = [x for x in all if x not in exclusions] random.choice(remaining)

与Niranjan的答案类似,但不需要列表理解

import numpy as np
import pandas as pd

exlcusion_list = [43606,125490]

free_ids = np.arange(40000, 200000)
free_ids = free_ids[~np.isin(free_ids, exlcusion_list)]

def get_ids(client_names):
    new_client_ids = np.random.choice(free_ids, len(client_names), replace=False)

    return pd.DataFrame(data=new_client_ids, index=client_names, columns=["id"])

print(get_ids(["Bob", "Fred", "Max"]))

          id
Bob   125205
Fred  185058
Max    86158
exclusions = [43606,125490,...]
def ID_Generator(new_clients): # This is a list of new client

  new_client_IDs = []

  while len(new_client_IDs) < len(new_clients):
    ID = randint(40000, 200000)
    if ID not in exclusions:
      new_client_IDs.append(ID)
    if list(dict.fromkeys(new_client_IDs)):
      new_client_IDs = list(dict.fromkeys(new_client_IDs))

相关问题 更多 >