You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写验证sAMAccountName是否在排除列表中的Python函数?

账户排除校验函数的实现与规范优化

需求说明

  • 编写is_account_excluded()函数,将从encoded_users_from_LDAP.json中遍历得到的sAMAccountName与addc_accounts_excluded.json中的排除规则比对
  • 主循环中通过if is_account_excluded(sAMAccountName) == False:筛选非排除账户

初始代码片段

import json

with open("addc_accounts_excluded.json", 'r', encoding="UTF-8") as file:
    data = json.load(file)
    excluded_users = data['sAMAccountName']

with open("encoded_users_from_LDAP.json", 'r', encoding="UTF-8") as file:
    data = json.load(file)
    retrived_users = data['entries']


def is_account_excluded(): # this what I need to validate accounts


for user in retrived_users:
    attributes = user['attributes']
    sAMAccountName = attributes['sAMAccountName']
    if is_account_excluded(sAMAccountName) == False:
        print(sAMAccountName)
        print(attributes['cn'])    

已实现的可运行函数

你自行编写了可运行的函数,但不确定写法是否规范:

def is_account_excluded(suspect):
    account = False
    for account_checked in excluded_users:
        if (account_checked == suspect):
            account = True
    return account

规范优化建议

你的代码能正常运行,但可以从性能和可读性两方面优化:

  1. 用成员运算符替代手动循环
    Python的in运算符可以直接判断元素是否在序列中,比手动遍历循环更简洁高效,直接写成:

    def is_account_excluded(suspect):
        return suspect in excluded_users
    
  2. 将排除列表转为集合提升查询性能
    如果excluded_users是大列表,查询时间复杂度为O(n);转为集合后查询时间复杂度降为O(1),性能提升明显:

    # 加载排除列表时转为集合
    with open("addc_accounts_excluded.json", 'r', encoding="UTF-8") as file:
        data = json.load(file)
        excluded_users = set(data['sAMAccountName'])
    
  3. 简化条件判断写法
    函数名is_account_excluded已经清晰表达返回True代表账户被排除,主循环的判断可以简化为更符合Python风格的写法:

    if not is_account_excluded(sAMAccountName):
        print(sAMAccountName)
        print(attributes['cn'])
    
  4. 修正拼写错误
    原代码中retrived_users拼写错误,正确应为retrieved_users,规范的变量名能提升代码可读性。

内容的提问来源于stack exchange,提问作者Kubix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 15:35:49