【发布时间】: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