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

基于随机字典的Python登录系统:随机字典元素访问问题

随机字典登录系统:无法访问随机选择的字典元素问题

我想要创建一个使用随机字典的登录系统,目前遇到的问题是:随机选择字典元素后,无法访问这些元素。我曾尝试使用iter来访问元素,但行不通,希望能获得解决方案,也给遇到类似问题的开发者提供参考。

附原代码:

import time
import random
import string

d = {
    'l1' : 'p1', 'l2' : 'p2'
}

d1 = random.choice(list(l.items()))

def d2(l, p):
    d_l = print(l)
    d_p = input("Enter the Answer: ")

    if d_p == p:
        print("Login Successful.")
    else:
        print("Your Answer was not correct.")
        print("Process will be terminated")
        time.sleep(5)

d2(#Here is the Problem)

问题分析与修复方案

你的代码有两个核心问题:

  1. 变量名错误:list(l.items())中的l是未定义变量,应该替换为实际的字典名d。
  2. 元组未拆解:random.choice(list(d.items()))返回的是一个键值对元组(比如('l1', 'p1')),直接把这个元组传给d2会导致参数不匹配,需要把元组的两个元素分别传入函数。

修正后的完整代码

import time
import random

d = {
    'l1' : 'p1', 'l2' : 'p2'
}

# 从字典的键值对中随机选一个,直接拆解为键和密码
selected_key, selected_pwd = random.choice(list(d.items()))

def d2(l, p):
    print(l)  # print无返回值,无需赋值给变量
    d_p = input("Enter the Answer: ")

    if d_p == p:
        print("Login Successful.")
    else:
        print("Your Answer was not correct.")
        print("Process will be terminated")
        time.sleep(5)

# 传入拆解后的两个参数
d2(selected_key, selected_pwd)

另一种简洁写法

如果你不想提前拆解元组,可以在调用d2时用*操作符直接解包元组:

d1 = random.choice(list(d.items()))
d2(*d1)

额外优化点

  • 原代码中的import string未被使用,可以删除,减少冗余。
  • d_l = print(l)是无效赋值,print()函数不会返回任何有效值,直接调用print(l)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:45:49