当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Matrix转String用法及代码示例


给定一个矩阵,我们的任务是编写一个 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:使用Python 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))

输出:

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:使用Python map()用法及代码示例+Python join()用法及代码示例

在此,元素内部连接的任务是使用 map() 扩展到每个字符。其余所有函数与上层方法类似。

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




相关用法


注:本文由纯净天空筛选整理自manjeet_04大神的英文原创作品 Python Program to Convert Matrix to String。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。