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

Python 3.7中不区分大小写比对两个列表的代码简化方案咨询

不区分大小写校验用户名的简化实现方案

你可以通过「推导式+集合存储」的方式大幅简化代码,同时提升校验效率,优化后代码如下:

current_users = ['ana', 'JohN', 'sweeny', 'Bobcat', 'anthony']
# 集合推导式直接生成全小写的用户名集合,查找效率远高于列表
current_users_lower = {user.lower() for user in current_users}

new_users = ['polo', 'joHn', 'lamer', 'johan', 'boBcat']

if new_users:
    for new_user in new_users:
        if new_user.lower() in current_users_lower:
            print(f"Usernames are case sensitive - username {new_user} is taken, please choose another one and try again!")
        else:
            print(f"Registration successful, your username is {new_user}")
else:
    print("No usernames to input")

主要优化点:

  • 替换了原有「复制列表+循环逐元素修改」的冗余逻辑,用一行集合推导式直接完成所有已有用户名的小写转换,代码更简洁易读
  • 用集合存储小写用户名,in匹配操作的时间复杂度从列表的O(n)降低到O(1),如果后续系统已有用户名数量很大,校验效率会有非常明显的提升
  • 用f-string格式化输出字符串,相比原来的字符串拼接写法更简洁,同时修正了原代码中successfull的拼写错误

如果你的业务场景允许直接修改原有current_users列表,也可以用列表推导式生成小写列表,不过集合存储是更推荐的工程实践,性能优势更突出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 18:27:02