将字符串矩阵表示转换为矩阵的Python程序
给定一个带有矩阵表示的字符串,这里的任务是编写一个将其转换为矩阵的Python程序。
Input : test_str = “[gfg,is],[best,for],[all,geeks]”
Output : [[‘gfg’, ‘is’], [‘best’, ‘for’], [‘all’, ‘geeks’]]
Explanation : Required String Matrix is converted to Matrix with list as data type.
Input : test_str = “[gfg,is],[for],[all,geeks]”
Output : [[‘gfg’, ‘is’], [‘for’], [‘all’, ‘geeks’]]
Explanation : Required String Matrix is converted to Matrix with list as data type.
方法 1:使用 split() 和正则表达式
在这种情况下,使用适当的正则表达式构建一个普通列表,split() 执行获取 2D 矩阵内部维度的任务。
例子:
Python3
import re
# initializing string
test_str = "[gfg,is],[best,for],[all,geeks]"
# printing original string
print("The original string is : " + str(test_str))
flat_1 = re.findall(r"\[(.+?)\]", test_str)
res = [sub.split(",") for sub in flat_1]
# printing result
print("The type of result : " + str(type(res)))
print("Converted Matrix : " + str(res))
Python3
# Python3 code to demonstrate working of
# Convert String Matrix Representation to Matrix
# Using json.loads()
import json
# initializing string
test_str = '[["gfg", "is"], ["best", "for"], ["all", "geeks"]]'
# printing original string
print("The original string is : " + str(test_str))
# inbuild function performing task of conversion
# notice input
res = json.loads(test_str)
# printing result
print("The type of result : " + str(type(res)))
print("Converted Matrix : " + str(res))
输出:
The original string is : [gfg,is],[best,for],[all,geeks]
The type of result :
Converted Matrix : [[‘gfg’, ‘is’], [‘best’, ‘for’], [‘all’, ‘geeks’]]
方法 2:使用 json.loads()
在这里,转换为矩阵的任务是使用 JSON 库的 load() 未构建方法完成的。
例子:
蟒蛇3
# Python3 code to demonstrate working of
# Convert String Matrix Representation to Matrix
# Using json.loads()
import json
# initializing string
test_str = '[["gfg", "is"], ["best", "for"], ["all", "geeks"]]'
# printing original string
print("The original string is : " + str(test_str))
# inbuild function performing task of conversion
# notice input
res = json.loads(test_str)
# printing result
print("The type of result : " + str(type(res)))
print("Converted Matrix : " + str(res))
输出:
The original string is : [[“gfg”, “is”], [“best”, “for”], [“all”, “geeks”]]
The type of result :
Converted Matrix : [[‘gfg’, ‘is’], [‘best’, ‘for’], [‘all’, ‘geeks’]]