Python|获取元组元素数据类型
元组可以是各种数据类型的集合,与简单的数据类型不同,获取元组每个元素的类型的常规方法是不可能的。为此,我们需要有不同的方法来完成这项任务。让我们讨论可以执行此任务的某些方式。
方法 #1:使用map() + type()
使用此函数是执行此任务的最常规和最佳方式。在此,我们只允许map()
将使用type()
查找数据类型的逻辑扩展到元组的每个元素。
# Python3 code to demonstrate working of
# Get tuple element data types
# Using map() + type()
# Initializing tuple
test_tup = ('gfg', 1, ['is', 'best'])
# printing original tuple
print("The original tuple is : " + str(test_tup))
# Get tuple element data types
# Using map() + type()
res = list(map(type, test_tup))
# printing result
print("The data types of tuple in order are : " + str(res))
输出 :
The original tuple is : ('gfg', 1, ['is', 'best'])
The data types of tuple in order are : [, , ]
方法 #2:使用 collections.Sequence + isinstance() + type()
我们可以使用上述功能的组合来执行此任务。使用此方法的另一个优点是,如果它的类型是复杂数据类型,它还为我们提供每个元素的长度。
# Python3 code to demonstrate working of
# Get tuple element data types
# Using collections.Sequence + isinstance() + type()
import collections
# Initializing tuple
test_tup = ('gfg', 1, ['is', 'best'])
# printing original tuple
print("The original tuple is : " + str(test_tup))
# Get tuple element data types
# Using collections.Sequence + isinstance() + type()
res = [(type(ele), len(ele) if isinstance(ele, collections.Sequence) else None)
for ele in test_tup]
# printing result
print("The data types of tuple in order are : " + str(res))
输出 :
The original tuple is : ('gfg', 1, ['is', 'best'])
The data types of tuple in order are : [(, 3), (, None), (, 2)]