Python - 拆分异构类型列表
有时,我们可能会使用多种数据类型,在这些情况下,我们可能会遇到问题,我们收到的列表可能包含来自不同数据类型的元素。让我们讨论可以执行此任务的某些方式。
方法 #1:使用列表理解 + isinstance()
上述两种功能的组合可用于执行此任务。在此,我们只是使用不同的列表推导提取相似的元素类型,并使用 isinstance() 检测类型。
Python3
# Python3 code to demonstrate working of
# Split heterogeneous type list
# using list comprehension + isinstance
# initialize list
test_list = ['gfg', 1, 2, 'is', 'best']
# printing original list
print("The original list : " + str(test_list))
# Split heterogeneous type list
# using list comprehension + isinstance
res_str = [ele for ele in test_list if isinstance(ele, str)]
res_int = [ele for ele in test_list if isinstance(ele, int)]
# printing result
print("Integer list : " + str(res_int))
print("String list : " + str(res_str))
Python3
# Python3 code to demonstrate working of
# Split heterogeneous type list
# using defaultdict() + loop
from collections import defaultdict
# initialize list
test_list = ['gfg', 1, 2, 'is', 'best']
# printing original list
print("The original list : " + str(test_list))
# Split heterogeneous type list
# using defaultdict() + loop
res = defaultdict(list)
for ele in test_list:
res[type(ele)].append(ele)
# printing result
print("Integer list : " + str(res[int]))
print("String list : " + str(res[str]))
输出 :
The original list : ['gfg', 1, 2, 'is', 'best']
Integer list : [1, 2]
String list : ['gfg', 'is', 'best']
方法 #2:使用 defaultdict() + 循环
这是可以解决此问题的另一种方式。在此,我们将列表初始化为 defaultdict() 的数据类型并循环遍历每个元素并将每个数据类型列表保存在 defaultdict 中。
Python3
# Python3 code to demonstrate working of
# Split heterogeneous type list
# using defaultdict() + loop
from collections import defaultdict
# initialize list
test_list = ['gfg', 1, 2, 'is', 'best']
# printing original list
print("The original list : " + str(test_list))
# Split heterogeneous type list
# using defaultdict() + loop
res = defaultdict(list)
for ele in test_list:
res[type(ele)].append(ele)
# printing result
print("Integer list : " + str(res[int]))
print("String list : " + str(res[str]))
输出 :
The original list : ['gfg', 1, 2, 'is', 'best']
Integer list : [1, 2]
String list : ['gfg', 'is', 'best']