Python|检查元组中的订单特定数据类型
有时,在处理记录时,我们可能会遇到一个问题,即我们需要测试在后端填写表单等时插入的数据类型的正确顺序。这些测试通常在 Web 开发时在前端处理,但也建议在后端进行测试。为此,我们有时需要根据记录的顺序检查记录的数据类型。让我们讨论可以执行此任务的某些方式。
方法 #1:使用链式 if 和 isinstance()
可以使用上述功能的组合来执行此任务。在此,我们只需要使用 isinstance() 测试数据类型,并检查我们使用链式 if 语句的元组的每个元素。
Python3
# Python3 code to demonstrate working of
# Check order specific data type in tuple
# Using chained if and isinstance()
# Initializing tuple
test_tup = ('gfg', ['is', 'best'], 1)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# Check order specific data type in tuple
# Using chained if and isinstance()
res = isinstance(test_tup, tuple)\
and isinstance(test_tup[0], str)\
and isinstance(test_tup[1], list)\
and isinstance(test_tup[2], int)
# printing result
print("Does all the instances match required data types in order ? : " + str(res))
Python3
# Python3 code to demonstrate working of
# Check order specific data type in tuple
# Using map() + type() + isinstance()
# Initializing tuple
test_tup = ('gfg', ['is', 'best'], 1)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# data type order list
data_list = [str, list, int]
# Check order specific data type in tuple
# Using map() + type() + isinstance()
res = isinstance(test_tup, tuple) and list(map(type, test_tup)) == data_list
# printing result
print("Does all the instances match required data types in order ? : " + str(res))
输出 :
The original tuple is : ('gfg', ['is', 'best'], 1)
Does all the instances match required data types in order ? : True
方法 #2:使用 map() + type() + isinstance()
上述功能的组合也可以用来完成这个任务。元组中每个元素的类型检查由 map() 扩展。这种方法的优点是它允许我们预先将数据类型排序定义为列表。
Python3
# Python3 code to demonstrate working of
# Check order specific data type in tuple
# Using map() + type() + isinstance()
# Initializing tuple
test_tup = ('gfg', ['is', 'best'], 1)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# data type order list
data_list = [str, list, int]
# Check order specific data type in tuple
# Using map() + type() + isinstance()
res = isinstance(test_tup, tuple) and list(map(type, test_tup)) == data_list
# printing result
print("Does all the instances match required data types in order ? : " + str(res))
输出 :
The original tuple is : ('gfg', ['is', 'best'], 1)
Does all the instances match required data types in order ? : True