Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的列表将仅返回第一行_Python - Fatal编程技术网

python中的列表将仅返回第一行

python中的列表将仅返回第一行,python,Python,我在单独的文本文件中有两个列表,“消息”和“代码”。我的程序将打开它们并读取它们。我的程序是一个代码兑换器,它将接受一个代码并将其兑换为一条消息 lstCodes = open("codes.txt").readlines() lstMessages = open("messages.txt").readlines() 我使用下面的类接收用户输入作为代码 class DateCheck: def __init__(self, date1): self.date1 = d

我在单独的文本文件中有两个列表,“消息”和“代码”。我的程序将打开它们并读取它们。我的程序是一个代码兑换器,它将接受一个代码并将其兑换为一条消息

lstCodes = open("codes.txt").readlines()
lstMessages = open("messages.txt").readlines()
我使用下面的类接收用户输入作为代码

class DateCheck:
    def __init__(self, date1):
        self.date1 = date1
        if date1 == datetime.date(xxxx,x,xx):
            print('Correct! \n')
            checkx = input('Are you ready to type in your final secret code? YES = 1, NO = 0: \n')
            dcodex = input("Enter Code: \n")
            #progressB=progress(50,.04)
            LoopCheck(checkx, dcodex)
        else:
            print('Wrong code')
一旦它要求用户输入代码,它就会将其传递给另一个类,该类将在文本文件中查找该代码,如果找到,则从messages.txt返回消息

class LoopCheck:
    def __init__(self, check, code):
        self.check = check
        self.code = code
        if code in lstCodes:
            print(lstMessages[lstCodes.index(code)])
        else:
            print("Wrong Code")
这就是问题所在,它只适用于code.txt中的第一个代码和message.txt中的第一条消息。当我输入正确的代码2时,它返回“错误”。我试着看看我是如何阅读清单的,但我不知道我做错了什么。我肯定这是个小错误,但我一直没能弄明白

#messages.txt
message1
message2

#codes.txt
xxxx
xxxx

最好使用字典:

codes = {}
with open("codes.txt") as cod_fobj, open("messages.txt") as mess_fobj:
    for code, mess in zip(cod_fobj, mess_fobj):
        codes[code.strip()] = mess.strip()
现在:

支票可能如下所示:

if code in codes:
    print(codes[code])
else:
    print("Wrong Code")
或:


我想我知道是怎么回事了。我将
codes.txt
上的格式更改为:

#codes.txt
xxxx, xxxx, xxxx

我还将
lstCodes=open(“code.txt”).readlines()
更改为
lstCodes=open(“code.txt”).read().split(',')
,因此现在当我在
code.txt
中查找代码时,它会返回其索引,然后我会在
messages.txt
上查找索引号并返回与其相关的消息

删除你的类。这是简单的函数,所以将它们作为函数编写。为什么在
\uuu init\uuu
中使用
input()
?既然你的类只有
\u init\u
你应该使用closure我们能看到你的
lstCodes
变量吗?@SteveJessop我用
print(lstCodes.index(code))照你说的做了
要在列表中找到
代码
,解释器返回
值错误:“ykse”不在列表中
@NotAnAmbiTurner
lstCodes
包含一个由4个字母组成的代码列表,如果这是您的意思,请输入。我已经找到了方法,但我也会尝试一下。谢谢
try:
    print(codes[code])
except KeyError:
    print("Wrong Code")
#codes.txt
xxxx, xxxx, xxxx