📜  Python - 将整数矩阵转换为字符串矩阵

📅  最后修改于: 2022-05-13 01:54:50.736000             🧑  作者: Mango

Python - 将整数矩阵转换为字符串矩阵

给定一个具有整数值的矩阵,将每个元素转换为字符串。

方法 #1:使用 str() + 列表理解

以上方法的组合可以解决这个问题。在这里,我们使用 str() 执行转换,并使用列表理解来迭代所有元素。

Python3
# Python3 code to demonstrate working of 
# Convert Integer Matrix to String Matrix
# Using str() + list comprehension
  
# initializing list
test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
  
# printing original list
print("The original list : " + str(test_list))
  
# using str() to convert each element to string 
res = [[str(ele) for ele in sub] for sub in test_list]
  
# printing result 
print("The data type converted Matrix : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Convert Integer Matrix to String Matrix
# Using str() + map()
  
# initializing list
test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
  
# printing original list
print("The original list : " + str(test_list))
  
# using map() to extend all elements as string  
res = [list(map(str, sub)) for sub in test_list]
  
# printing result 
print("The data type converted Matrix : " + str(res))


输出
The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
The data type converted Matrix : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6'], ['9', '3', '6']]

方法 #2:使用 str() + map()

以上功能的组合也可以解决这个问题。在这里,我们使用 map() 将字符串转换扩展到所有行元素。

蟒蛇3

# Python3 code to demonstrate working of 
# Convert Integer Matrix to String Matrix
# Using str() + map()
  
# initializing list
test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
  
# printing original list
print("The original list : " + str(test_list))
  
# using map() to extend all elements as string  
res = [list(map(str, sub)) for sub in test_list]
  
# printing result 
print("The data type converted Matrix : " + str(res))
输出
The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
The data type converted Matrix : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6'], ['9', '3', '6']]