Python – 双拆分字符串到矩阵
给定一个字符串,执行双重拆分,第一个用于行,第二个用于单个元素,以便给定的字符串可以转换为矩阵。
例子:
Input : test_str = ‘Gfg,best*for,all*geeks,and,CS’, row_splt = “*”, ele_splt = “,”
Output : [[‘Gfg’, ‘best’], [‘for’, ‘all’], [‘geeks’, ‘and’, ‘CS’]]
Explanation : String split by rows, and elements by respective delims.
Input : test_str = ‘Gfg!best*for!all*geeks!and!CS’, row_splt = “*”, ele_splt = “!”
Output : [[‘Gfg’, ‘best’], [‘for’, ‘all’], [‘geeks’, ‘and’, ‘CS’]]
Explanation : String split by rows, and elements by respective delims.
方法 #1:使用 split() + 循环
在此,第一个 split() 用于构造 Matrix 的行,然后嵌套 split() 以获取各个元素之间的分离。
Python3
# Python3 code to demonstrate working of
# Double Split String to Matrix
# Using split() + loop
# initializing string
test_str = 'Gfg,best#for,all#geeks,and,CS'
# printing original string
print("The original string is : " + str(test_str))
# initializing row split char
row_splt = "#"
# initializing element split char
ele_splt = ","
# split for rows
temp = test_str.split(row_splt)
res = []
for ele in temp:
# split for elements
res.append(ele.split(ele_splt))
# printing result
print("String after Matrix conversion : " + str(res))
Python3
# Python3 code to demonstrate working of
# Double Split String to Matrix
# Using list comprehension + split()
# initializing string
test_str = 'Gfg,best#for,all#geeks,and,CS'
# printing original string
print("The original string is : " + str(test_str))
# initializing row split char
row_splt = "#"
# initializing element split char
ele_splt = ","
# split for rows
temp = test_str.split(row_splt)
# using list comprehension as shorthand
res = [ele.split(ele_splt) for ele in temp]
# printing result
print("String after Matrix conversion : " + str(res))
输出:
The original string is : Gfg,best#for,all#geeks,and,CS
String after Matrix conversion : [[‘Gfg’, ‘best’], [‘for’, ‘all’], [‘geeks’, ‘and’, ‘CS’]]
方法 #2:使用列表理解 + split()
这是可以执行此任务的另一种方式。在此,我们使用类似的过程,但单线解决问题。
蟒蛇3
# Python3 code to demonstrate working of
# Double Split String to Matrix
# Using list comprehension + split()
# initializing string
test_str = 'Gfg,best#for,all#geeks,and,CS'
# printing original string
print("The original string is : " + str(test_str))
# initializing row split char
row_splt = "#"
# initializing element split char
ele_splt = ","
# split for rows
temp = test_str.split(row_splt)
# using list comprehension as shorthand
res = [ele.split(ele_splt) for ele in temp]
# printing result
print("String after Matrix conversion : " + str(res))
输出:
The original string is : Gfg,best#for,all#geeks,and,CS
String after Matrix conversion : [[‘Gfg’, ‘best’], [‘for’, ‘all’], [‘geeks’, ‘and’, ‘CS’]]