Python - 从混合矩阵中提取字符串元素
给定一个矩阵,提取所有字符串数据类型的元素。
Input : test_list = [[5, 6, 3], [“Gfg”, 3], [9, “best”, 4]]
Output : [‘Gfg’, ‘best’]
Explanation : All strings are extracted.
Input : test_list = [[“Gfg”, 3], [9, “best”, 4]]
Output : [‘Gfg’, ‘best’]
Explanation : All strings are extracted.
方法 #1:使用列表理解 + isinstance()
以上功能的组合可以解决这个问题。在这里,我们使用列表理解来迭代嵌套列表,并使用isinstance()检查字符串实例。
Python3
# Python3 code to demonstrate working of
# Extract String elements from Mixed Matrix
# Using list comprehension + isinstance()
# initializing lists
test_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]]
# printing original list
print("The original list : " + str(test_list))
# strings are extracted using isinstance()
res = [ele for sub in test_list for ele in sub if isinstance(ele, str)]
# printing result
print("The String instances : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract String elements from Mixed Matrix
# Using chain.from_iterables + list comprehension + isinstance()
from itertools import chain
# initializing lists
test_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]]
# printing original list
print("The original list : " + str(test_list))
# strings are extracted using isinstance()
# using chain.from_iterables()
res = [ele for ele in chain.from_iterable(test_list) if isinstance(ele, str)]
# printing result
print("The String instances : " + str(res))
输出
The original list : [[5, 6, 3], ['Gfg', 3, 'is'], [9, 'best', 4]]
The String instances : ['Gfg', 'is', 'best']
方法 #2:使用 chain.from_iterables() + 列表推导 + isinstance()
这是可以执行此任务的另一种方式。整个矩阵被展平,然后isintance()应用于它以检查展平列表中的字符串元素。
蟒蛇3
# Python3 code to demonstrate working of
# Extract String elements from Mixed Matrix
# Using chain.from_iterables + list comprehension + isinstance()
from itertools import chain
# initializing lists
test_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]]
# printing original list
print("The original list : " + str(test_list))
# strings are extracted using isinstance()
# using chain.from_iterables()
res = [ele for ele in chain.from_iterable(test_list) if isinstance(ele, str)]
# printing result
print("The String instances : " + str(res))
输出
The original list : [[5, 6, 3], ['Gfg', 3, 'is'], [9, 'best', 4]]
The String instances : ['Gfg', 'is', 'best']