追加fi时,“TypeError:'in<string>”需要字符串作为左操作数,而不是list”

2024-05-14 07:24:39 发布

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

我目前正在做一个小程序,以便创建随机序列号。如果序列号已经存在,它将废弃这个想法。如果没有,它会检查序列号是否曾经存在,现在是否无效。如果不是这样,它将附加到一个文件。我希望这个程序能够运行无限次而不会引起问题,直到最后一点,都不会。在

我的代码如下:

def GenerateSerial():
    '''This will generate a new serial number based on pre-existing'''
    HexidecimalKey = open('Hexidecimal_No_Spaces.txt', 'r')
    Serials = open('ConcurrentSerials.txt', 'r')
    Void = open('VoidSerials.txt', 'r')
    GenerationKey = HexidecimalKey.read()
    currentSerials = Serials.read()
    voidSerials = Void.read()
    ###print(GenerationKey)
    SizeOfSerial = random.randint(3,6)
    NewSerial = random.sample(GenerationKey, SizeOfSerial)
    print(NewSerial)
    NewSerial1 = ' '.join(str(x) for x in NewSerial)
    print(NewSerial1)
    for serial in currentSerials:
        if NewSerial in currentSerials:
            print("That serial is already in the current serials")
            print("Scrapping serial and restarting generation")
    for serials in voidSerials:
        if NewSerial in voidSerials:
            print("That serial has already been previously used and voided")
            print("It cannot be used again")
    else:
        Serials.close()
        ###Serials = open('ConcurrentSerials.txt', 'w')
        with open("ConcurrentSerials.txt", "a") as myfile:
            myfile.write(NewSerial1 + "\n")
        ###serialsappend = Serials.read()
        ###Serials.write(NewSerial)

当我运行一次代码时,它会附加'ConcurrentSerials.txt'生成序列号的文件。但是,当我第二次运行它时,我得到了一个错误:

^{pr2}$

有人能帮我理解为什么会这样吗?我试着四处寻找并纠正这个过程,但它在任何程度上都不起作用。在

谢谢你的帮助

约瑟夫。在


Tags: intxtforreadserialopen序列号print
1条回答
网友
1楼 · 发布于 2024-05-14 07:24:39

错误表示您正在尝试查看列表是否在字符串中。在

NewSerialis of type ^{}。在

currentSerialsis of type ^{}。在

而不是:

for serial in currentSerials:
    if NewSerial in currentSerials:
        ...

您可能需要:

^{pr2}$

这将检查文件的全部内容。如果不是很大,那也不是问题。但是如果你想提高效率,最好是把所有当前序列读入一个集合,然后执行集合交集。在

相关问题 更多 >

    热门问题