【问题标题】:How to check if all items in a list are of the same type?如何检查列表中的所有项目是否属于同一类型?
【发布时间】:2020-06-02 00:32:48
【问题描述】:

我正在尝试使用一个函数来验证列表中的所有项目是否属于同一类型。请参阅“检查整数类型”部分。但是,无论当前输入如何,我的函数的该部分都会返回 False。

让该部分检查输入类型(浮点数、字符串、整数)的最佳方法是什么,如果它们不完全相同则返回 False,否则返回 True?如果它们的类型不同,则让函数请求另一个输入。

def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for integer type across the list:
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

#    except:
#        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()

编辑:

我现在尝试将几个答案合并到一段代码中:

def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for type across the list:
    try:
        typecheck = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
    except typecheckerror:
        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()

关于我如何修改它以完成我想要达到的目标的任何指示?如果我输入 (a,b,c),它应该返回“c”,如果我输入 (1,2,a),它应该给我错误消息。当我打印类型检查的值时,即使我输入类似 1,2,a 的值,它也会返回“True”值。

【问题讨论】:

  • input() 应该返回一个字符串,所以我不确定value 怎么可能是True。运行 print([isinstance(item, int) for item in maxlist]) 和 print([type(item) for item in maxlist]) 会得到什么
  • 如果这是 Python 3,如标签所示,input() 将始终生成一个字符串。 (在 Python 2 中, input() 会将用户输入作为 Python 代码进行评估,因此结果可能是任意类型)。如果您想接受 Python 语法(例如,用户按字面意思输入 "foo" 以获取字符串),请将 input() 的结果传递给 ast.literal_eval。
  • 'bool' 对象不可调用

标签: python python-3.x list sorting types


【解决方案1】:

您可以通过更新此部分首先检查输入值类型:

Value1 = input_int ('Enter the first value here:  \n')
Value2 = input_int ('Enter the second value here:  \n')
Value3 = input_int ('Enter the third value here:  \n')

使用这个自定义输入函数:

def input_int(input_msg: str) -> int:
    try:
        val = input(input_msg)
        return int(val)
    except Exception:
        return input_int(input_msg)

【讨论】:

  • 递归什么时候停止?
  • 好的,现在代码可以运行了,但是我遇到了 Austin 引用的递归问题。
  • 抱歉函数更新了,因为输入值是字符串,所以在这种情况下无法使用isinstance
  • 如果我输入字母而不是数字,仍然存在递归问题
【解决方案2】:

最好的方法是在“try/catch”中将值实际转换为您想要的类型。

所以如果你想检查整数,你可以这样做:

try: val = int(Value1) except ValueError: print("This is not a number... Please write a real value")

您也可以对浮动等执行相同的操作。

你也可以使用 isdigit()

if(Value1.isdigit()):
   print("Finally, it's a number!")
else:
   print("Type a real number please!")

【讨论】:

    【解决方案3】:

    根据问题标题,您可以使用以下方法检查所有值是否属于同一类型:

    value = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
    

    【讨论】:

      【解决方案4】:

      您可以使用列表推导并比较两者:

      def func(list1):
          list2 = [x for x in list1 if type(x) == int]
          if list1 == list2:
              return True
          else:
              return False
      

      【讨论】:

        【解决方案5】:

        您的代码的以下部分总是返回 False,而不是 True 为什么?跟随cmets

        def maxOfThree():
            #Ask users to input values
            # What do you think the data type fo Value1 to 3?
            Value1 = input('Enter the first value here:  \n')
            Value2 = input('Enter the second value here:  \n')
            Value3 = input('Enter the third value here:  \n')
            # When we read any data from user via input() it collect 
            # the data in String data type
        
            #store values in a list
            # Now you stored all the String into list and applying
            # sort operation on Strings
            maxlist = [Value1, Value2, Value3]
            maxlist.sort()
        
            #Check for integer type across the list:
            # Now the maxlist contains sorted Strings, Now you are 
            # comparing it's data type with Int which will always
            # fail and it returns **False**
            value = all(isinstance(item, int) for item in maxlist)
            print(value)
        
            print('\n')
            print('The maximum of these values is: \n', maxlist[-1])
        
        maxOfThree()
        

        例子:

        Input: 
        Enter the first value here:
        text
        Enter the second value here:
        abc
        Enter the third value here:
        1233
        False -> your are comparing list of Strings to Int data type
                 with isinstance(item, int)
        
        Output:
        The maximum of these values is:
         text
        

        代码:

        def maxOfThree():
            #Ask users to input values
            Value1 = input('Enter the first value here:  \n')
            Value2 = input('Enter the second value here:  \n')
            Value3 = input('Enter the third value here:  \n')
        
            #store values in a list by converting to int
            maxlist = []
            # wrapped the conversion code in try block 
            # if any text inputs are given
            try:
                maxlist = [int(each) for each in [Value1, Value2, Value3]]
            except Exception as e:
                print("Couldn't able to convert to integer")
                raise(e)
            maxlist.sort()
        
            #Check for integer type across the list:
            value = all(isinstance(item, int) for item in maxlist)
            print(value)
        
            print('\n')
            print('The maximum of these values is: \n', maxlist[-1])
        
        maxOfThree()
        

        【讨论】:

        • 是的,我的错误现在默认返回 False。
        • 问题是,该函数应该也可以对字母进行排序。所以它会返回 'c' 作为 (a,b,c) 列表中的最大排名
        • 你的意思是说它不会有数据类型的组合?如果跨越相同的数据类型,那么你的函数需要采取行动吗?并且输入可以是int、float、string
        • 是的,这是正确的,所以如果你尝试对 (1,2,'a') 进行排名,它会返回一个错误。并要求另一个输入。但是 ('d','e','g') 应该仍然可以工作
        【解决方案6】:

        完整的代码。

        def check_input_type(value): 
            try:
                value = int(value)
                print(f"Value {value} is an integer!")
                return value
            except ValueError:
                try:
                    value = float(value)
                    print(f"Value {value} is a float!")
                    return value
                except ValueError:
                    print(f"Value {value} is a string!")
                    return value
        
        def max_of_three():
            max_list = []
            while True:
                value = check_input_type(input(f"Please enter your value : "))
                if not max_list: # if list is empty, append first value.
                    max_list.append(value)
                elif type(max_list[0]) == type(value): # checks the next value's type if equal to the first index's type
                    max_list.append(value)
                else:
                    print("Sorry, I do not understand. Please try again.")
                if len(max_list) != 3:
                    continue
                return max_list
        
        listr = max_of_three()
        
        print(f"The maximum of these values {listr} is {max(listr)}!")
        

        【讨论】:

        • 我希望它也接受 str 和 float 输入,但它应该在三个输入 a、b、c 中返回一个值 'c'
        • 对不起,我昨晚已经睡了。我已经编辑了上面的代码。
        • 谢谢你,这很好用!我想作为一个思考练习,如果我希望该函数还检查用户输入的内容是否包含 only 整数或 only 字符串?
        • 您可以使用isnumeric()或isalpha()函数进行检查。
        猜你喜欢
        • 2012-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        相关资源
        最近更新 更多