Python – 将字符串转换为字符矩阵
有时,在处理字符串列表时,我们可能会遇到需要将列表中的字符串转换为单独的字符列表的问题。整体转换成矩阵。这可以在我们处理大量数据的数据科学领域有多种应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用列表推导
这是可以执行此任务的一种方式。在此,我们使用 list() 将字符串转换为字符列表,并将结果转换为所需的矩阵。
# Python3 code to demonstrate
# Convert Strings to Character Matrix
# using List comprehension
# Initializing list
test_list = ['gfg', 'is', 'best']
# printing original list
print("The original list is : " + str(test_list))
# Convert Strings to Character Matrix
# using List comprehension
res = [list(sub) for sub in test_list]
# printing result
print ("List String after conversion to Matrix : " + str(res))
输出 :
The original list is : [‘gfg’, ‘is’, ‘best’]
List String after conversion to Matrix : [[‘g’, ‘f’, ‘g’], [‘i’, ‘s’], [‘b’, ‘e’, ‘s’, ‘t’]]
方法 #2:使用loop + list()
这是执行此任务的蛮力方式。在此,我们运行循环并使用 list() 将每个字符串转换为字符列表。
# Python3 code to demonstrate
# Convert Strings to Character Matrix
# using loop + list()
# Initializing list
test_list = ['gfg', 'is', 'best']
# printing original list
print("The original list is : " + str(test_list))
# Convert Strings to Character Matrix
# using loop + list()
res = []
for sub in test_list:
res.append(list(sub))
# printing result
print ("List String after conversion to Matrix : " + str(res))
输出 :
The original list is : [‘gfg’, ‘is’, ‘best’]
List String after conversion to Matrix : [[‘g’, ‘f’, ‘g’], [‘i’, ‘s’], [‘b’, ‘e’, ‘s’, ‘t’]]