Как проверить, все ли элементы в списке одного типа? - PullRequest
0 голосов
/ 18 февраля 2020

Я пытаюсь заставить функцию проверить, что все элементы в списке имеют одинаковый тип. Смотрите раздел "проверка целочисленного типа". Тем не менее, этот раздел моей функции возвращает значение False независимо от того, какие данные введены в данный момент.

Каков наилучший способ проверки этого раздела на предмет типа ввода (float, string, integer), возврат 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()

Есть какие-нибудь указатели на то, как я могу изменить это, чтобы сделать то, к чему я пытаюсь добраться? Он должен вернуть 'c', если я введу (a, b, c), и выдаст мне сообщение об ошибке, если я введу (1,2, a). Когда я печатаю значение для проверки типов, оно возвращает значение «True», даже если я ввожу что-то вроде 1,2, a.

Ответы [ 6 ]

1 голос
/ 18 февраля 2020

Исходя из названия вопроса, вы можете проверить, если все значения имеют одинаковый тип , используя:

value = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
0 голосов
/ 18 февраля 2020

Полный код.

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)}!")
0 голосов
/ 18 февраля 2020

В следующем разделе вашего кода всегда возвращается False , а не True Почему? следуйте комментариям

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()
0 голосов
/ 18 февраля 2020

Вы можете использовать понимание списка и сравнить оба:

def func(list1):
    list2 = [x for x in list1 if type(x) == int]
    if list1 == list2:
        return True
    else:
        return False
0 голосов
/ 18 февраля 2020

Лучший способ - на самом деле привести значение в тип, который вы хотите, в "try / catch".

Поэтому, если вы хотите проверить целое число, вы должны сделать это так:

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

Вы можете сделать то же самое для float et c.

Также вы можете использовать isdi git ()

if(Value1.isdigit()):
   print("Finally, it's a number!")
else:
   print("Type a real number please!")
0 голосов
/ 18 февраля 2020

Сначала вы можете проверить тип входного значения, обновив этот раздел:

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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...