将矩阵转换为字符串的Python程序
给定一个矩阵,我们的任务是编写一个Python程序来转换为矩阵,使用不同的分隔符来分隔元素和行。
例子:
Input : test_list = test_list = [[1, 3, “gfg”], [2, “is”, 4], [“best”, 9, 5]], in_del, out_del = “,”, ” “
Output : 1,3,gfg 2,is,4 best,9,5
Explanation : Element in list separated by “,”, and lists separated by ” “.
Input : test_list = test_list = [[1, 3, “gfg”], [2, “is”, 4], [“best”, 9, 5]], in_del, out_del = “,”, “-“
Output : 1,3,gfg-2,is,4-best,9,5
Explanation : Element in list separated by “,”, and lists separated by “-“.
方法 #1:使用join() +列表理解
在这里,我们使用列表理解来执行迭代每行的每个元素的任务。使用 join() 对具有不同分隔符的元素和行进行内连接和外连接。
Python3
# Python3 code to demonstrate working of
# Convert Matrix to String
# Using list comprehension + join()
# initializing list
test_list = [[1, 3, "gfg"], [2, "is", 4], ["best", 9, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing delims
in_del, out_del = ",", " "
# nested join using join()
res = out_del.join([in_del.join([str(ele) for ele in sub]) for sub in test_list])
# printing result
print("Conversion to String : " + str(res))
Python3
# Python3 code to demonstrate working of
# Convert Matrix to String
# Using map() + join()
# initializing list
test_list = [[1, 3, "gfg"], [2, "is", 4], ["best", 9, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing delims
in_del, out_del = ",", " "
# nested join using join()
# map() for joining inner elements
res = out_del.join(in_del.join(map(str, sub)) for sub in test_list)
# printing result
print("Conversion to String : " + str(res))
输出:
The original list is : [[1, 3, ‘gfg’], [2, ‘is’, 4], [‘best’, 9, 5]]
Conversion to String : 1,3,gfg 2,is,4 best,9,5
方法 #2:使用map() + join()
在这种情况下,元素内部连接的任务是使用 map() 扩展到每个字符。其余的所有功能都类似于上层方法。
蟒蛇3
# Python3 code to demonstrate working of
# Convert Matrix to String
# Using map() + join()
# initializing list
test_list = [[1, 3, "gfg"], [2, "is", 4], ["best", 9, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing delims
in_del, out_del = ",", " "
# nested join using join()
# map() for joining inner elements
res = out_del.join(in_del.join(map(str, sub)) for sub in test_list)
# printing result
print("Conversion to String : " + str(res))
输出:
The original list is : [[1, 3, ‘gfg’], [2, ‘is’, 4], [‘best’, 9, 5]]
Conversion to String : 1,3,gfg 2,is,4 best,9,5