【问题标题】:List - int comparatives [closed]列表-int比较[关闭]
【发布时间】:2015-01-27 11:33:03
【问题描述】:

在这里,我试图从用户那里获取添加到列表中的输入,然后必须先验证列表,然后才能通过另一个函数运行它。我知道我需要更改一些东西才能使比较起作用:只能与整数一起使用,并且列表中的输入将是一个字符串。还有一个错误说“不可排序的类型:str()> int()。我该如何解决这个问题?

def strInput():
string = []
string = str(input("Please enter numbers from 1-999... "))
if validate(string):
    return string
else:
    strInput()

def validate(i):
    if i > 0 and i <= 999:
        return True
    else:
        strInput()

【问题讨论】:

    标签: python string list function int


    【解决方案1】:

    我想你想收集一个数字列表。下面的代码可以解决问题

    def validate(userInput):
        return userInput.isdigit() and int(userInput) > 0 and int(userInput) <= 999
    
    def getListOfNumbers():
        listOfNumbers = []
        while True:
            userInput = raw_input("Please enter a number from 1 to 999. Enter 0 to finish input: ")
            if userInput == '0':
                return listOfNumbers
            elif validate(userInput):
                listOfNumbers.append(int(userInput))
            #optional
            else:
                continue
    myList = getListOfNumbers()
    print myList
    

    【讨论】:

    • 非常感谢,这非常有效。非常感谢!
    【解决方案2】:

    应该是:要么这样做:

    if int(i) > 0 and int(i) <= 999:
    

    如果您在 python 3 input 中将输入作为字符串
    或者这样做:

    string = int(input("Please enter numbers from 1-999... "))
    

    【讨论】:

      【解决方案3】:

      希望对你有帮助

      def validate(i):
          try:
              num = int(i)
          except:
              return False
          return num > 0 and num <= 999
      
      def strInput():
          string = str(input("Please enter numbers from 1-999... "))
          if validate(string):
              return string
          else:
              return strInput()
      
      strings = []
      strings.append(strInput())
      strings.append(strInput())
      print (strings)
      

      打印出来

      Please enter numbers from 1-999... 1
      Please enter numbers from 1-999... a
      Please enter numbers from 1-999... 2
      ['1', '2']
      

      【讨论】:

        【解决方案4】:

        您只需要将字符串转换为整数。试试:

        def validate(i):
            if i.isdigit() and int(i) > 0 and int(i) <= 999:
                return True
            else:
                strInput()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-09-22
          • 1970-01-01
          • 1970-01-01
          • 2019-01-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多