python中的List只返回第一个lin

2024-03-28 09:38:14 发布

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

我有两个单独的文本文件列表,“消息”和“代码”。我的程序将打开它们并读取它们。我的程序是一个代码救赎者,将采取一个代码和赎回它的消息。你知道吗

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')

一旦它要求用户输入代码,它就会将其传递给另一个类,该类将在文本文件中查找该代码,如果找到则返回来自的消息消息.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")

问题是,它只适用于代码.txt第一条信息消息.txt. 当我输入正确的代码2时,它返回“错误”。我试着看看我是怎么看这些单子的,但我不知道我做错了什么。我肯定这是个小错误,但我还没弄明白。你知道吗

#messages.txt
message1
message2

#codes.txt
xxxx
xxxx

Tags: 代码self程序txt消息checkcodeopen
2条回答

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

#codes.txt
xxxx, xxxx, xxxx

我还将lstCodes = open("codes.txt").readlines()改为lstCodes = open("codes.txt").read().split(','),所以现在当我在code.txt中查找代码时,它会返回其索引,然后在messages.txt上查找索引号并返回与之相关的消息。你知道吗

最好使用字典:

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()

现在:

>>>> codes['code1']
'message1'

支票可以是这样的:

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

或:

try:
    print(codes[code])
except KeyError:
    print("Wrong Code")

相关问题 更多 >