Python – 将字符串组合成矩阵
有时在处理数据时,我们可以接收到字符串形式的单独数据,我们需要将它们编译成 Matrix 以供进一步使用。这可以在许多领域有应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用列表理解 + split() + zip()
上述功能的组合可用于执行此任务。在此,我们使用 zip() 将字符串组合成矩阵行元素,并使用 split 执行从字符串中提取单词的任务。
# Python3 code to demonstrate working of
# Combine Strings to Matrix
# Using list comprehension + zip() + split()
# initializing strings
test_str1 = "Gfg is best"
test_str2 = "1 2 3"
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Combine Strings to Matrix
# Using list comprehension + zip() + split()
res = [[idx, int(j)] for idx, j in zip(test_str1.split(' '), test_str2.split(' '))]
# printing result
print("Does Matrix after construction : " + str(res))
The original list 1 is : [‘Gfg’, ‘is’, ‘best’]
The original list 2 is : [[‘Gfg’, 1], [‘is’, 2], [‘best’, 1], [‘Gfg’, 4], [‘is’, 8], [‘Gfg’, 7]]
The dictionary after grouping : {‘is’: [2, 8], ‘Gfg’: [1, 4, 7], ‘best’: [1]}
方法 #2:使用map() + split() + zip()
上述功能的组合可用于执行此任务。这以与上述类似的方式执行。不同的是扩展的逻辑是使用map()完成的。
# Python3 code to demonstrate working of
# Combine Strings to Matrix
# Using map() + zip() + split()
# initializing strings
test_str1 = "Gfg is best"
test_str2 = "1 2 3"
# printing original strings
print("The original string 1 is : " + test_str1)
print("The original string 2 is : " + test_str2)
# Combine Strings to Matrix
# Using map() + zip() + split()
res = list(map(list, zip(test_str1.split(' '), map(int, test_str2.split(' ')))))
# printing result
print("Does Matrix after construction : " + str(res))
The original list 1 is : [‘Gfg’, ‘is’, ‘best’]
The original list 2 is : [[‘Gfg’, 1], [‘is’, 2], [‘best’, 1], [‘Gfg’, 4], [‘is’, 8], [‘Gfg’, 7]]
The dictionary after grouping : {‘is’: [2, 8], ‘Gfg’: [1, 4, 7], ‘best’: [1]}