當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。