Python – 矩阵数据类型校正
有时,在处理数据时,我们可能会遇到需要对列表数据类型进行纠正的问题,即在必要时将数字字符串转换为数字。这也可以以矩阵形式发生。让我们讨论可以执行此任务的某些方式。
方法 #1:使用列表理解 + isdigit()
这是可以执行此任务的方式之一。在此,我们迭代 Matrix 的每个元素并使用类型转换检查数字字符串,然后执行转换。
# Python3 code to demonstrate
# Matrix Data Type Rectification
# using isdigit() + list comprehension
# Initializing list
test_list = [['5', 'GFG'], ['1', '3'], ['is', '11'], ['1', 'best']]
# printing original list
print("The original list is : " + str(test_list))
# Matrix Data Type Rectification
# using isdigit() + list comprehension
res = [[int(ele) if ele.isdigit() else ele for ele in sub] for sub in test_list]
# printing result
print ("The rectified Matrix is : " + str(res))
输出 :
The original list is : [['5', 'GFG'], ['1', '3'], ['is', '11'], ['1', 'best']]
The rectified Matrix is : [[5, 'GFG'], [1, 3], ['is', 11], [1, 'best']]
方法 #2:使用map() + isdigit()
这是可以执行此任务的另一种方式。在此,我们使用 map() 而不是列表推导将逻辑扩展到每个元素。
# Python3 code to demonstrate
# Matrix Data Type Rectification
# using map() + isdigit()
# Initializing list
test_list = [['5', 'GFG'], ['1', '3'], ['is', '11'], ['1', 'best']]
# printing original list
print("The original list is : " + str(test_list))
# Matrix Data Type Rectification
# using map() + isdigit()
res = [list(map(lambda ele: int(ele) if ele.isdigit() else ele, sub)) for sub in test_list]
# printing result
print ("The rectified Matrix is : " + str(res))
输出 :
The original list is : [['5', 'GFG'], ['1', '3'], ['is', '11'], ['1', 'best']]
The rectified Matrix is : [[5, 'GFG'], [1, 3], ['is', 11], [1, 'best']]