【问题标题】:Fix errors for checking integers in lists [duplicate]修复检查列表中整数的错误[重复]
【发布时间】:2023-04-10 12:06:01
【问题描述】:

当我运行这段代码时;即使列表只包含数字,当它应该返回[1, 2, 3] 时,它仍然作为错误返回。我该如何解决这个问题?

def check_integer(a, b, c):

  if type([a, b, c]) !=  int:
    raise TypeError("Must be numbers.")
  else:
    return [a, b, c]

print (check_integer(1, 2, 3)) 

【问题讨论】:

标签: python list integer


【解决方案1】:

这是一种方法:

def check_integers(*args):

    if not all(isinstance(i, int) for i in args):
        raise TypeError("Must be numbers.")
    
    return list(args)

您可以在 isinstance 的第二个参数中添加其他类型作为元组 (ej.isinstance(var, (int, float)))。

【讨论】:

    【解决方案2】:

    一个通用的解决方案:

    def check_integer(*args):
        if not all([type(i) == int for i in [*args]]):
            raise TypeError("Must be numbers.")
    
        return args
    

    【讨论】:

      【解决方案3】:

      尝试使用all 并遍历每个元素:

      def check_integer(a, b, c):
      
          if not all(type(i)==int for i in [a,b,c]):
              raise TypeError("Must be numbers.")
          else:
              return [a, b, c]
      
      print (check_integer(1, 2, 3)) 
      

      [1, 2, 3]
      

      高效的做法:

      def check_integer(*params):
      
          if not all(type(i)==int for i in params):
              raise TypeError("Must be numbers.")
          else:
              return params
      
      print (check_integer(*[1,2,3])) 
      

      【讨论】:

        【解决方案4】:
        def check_integer(a, b, c):
        
          if not (type(a) is int and type(b) is int and type(c) is int):
            raise TypeError("Must be numbers.")
          else:
            return [a, b, c]
        
        
        print(check_integer(1, 2, 3))
        

        这是 正确的代码。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-05-14
          • 2021-09-03
          • 1970-01-01
          • 2020-12-16
          • 2012-12-06
          • 2011-01-22
          • 2016-10-19
          • 2017-05-17
          相关资源
          最近更新 更多