【问题标题】:TypeError: '<' not supported between instances of 'list' and 'int'TypeError: 'list' 和 'int' 的实例之间不支持'<'
【发布时间】:2020-03-03 09:39:54
【问题描述】:

我正在尝试在 Python 中运行一段简单的代码来尝试将文本文件放入列表中并收到以下错误消息:

TypeError: 'list' 和 'int' 的实例之间不支持'

这是代码:

def MAINLOOP ():
    import random
    listofkeywords = []
    attempts = 0
    complete = ([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
    while complete < 30:
        question = random.randint(0,14)
        print(question)

MAINLOOP()
def IMPORTKEYWORDS():
    thekeywords = open("keywords.txt","r")
    listofkeywords == thekeywords

【问题讨论】:

  • while 循环在那里做什么
  • 你想用while complete &lt; 30:这个行做什么?您尝试过什么来解决这个问题?
  • while 声明至少对我来说没有意义。这应该是长度还是什么?

标签: python


【解决方案1】:

while complete &lt; 30 行出错。 complete 是一个列表,您尝试将其与整数 30 进行比较?如果要比较列表长度,请使用while len(complete) &lt; 30

【讨论】:

  • 这不是解决办法。 while len(complete)
  • 我只是建议修复 TypeError?
【解决方案2】:

您正在一次比较整个列表。除非您使用 numpy,否则不支持此类比较。您的代码的修复方法是分别比较列表中的每个条目,如下所示:

def MAINLOOP ():
    import random
    listofkeywords = []
    attempts = 0
    complete = ([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
    for i in complete:
        if i <30:
            question = random.randint(0,14)
            print(question)

MAINLOOP()
def IMPORTKEYWORDS():
    thekeywords = open("keywords.txt","r")
    listofkeywords == thekeywords

【讨论】:

    猜你喜欢
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 2022-07-03
    • 1970-01-01
    • 2020-09-07
    • 2020-11-13
    • 2021-01-15
    相关资源
    最近更新 更多