Python|将字符矩阵转换为单个字符串
有时,在使用Python字符串时,我们可以选择执行将字符矩阵转换为单个字符串的任务。这可以在我们需要处理数据的领域中应用。让我们讨论一下我们可以执行此任务的某些方法。
方法 #1:使用join()
+ 列表推导
上述功能的组合可用于执行此任务。在此,我们只是迭代所有列表并使用 join() 加入它们。
# Python3 code to demonstrate working of
# Convert Character Matrix to single String
# Using join() + list comprehension
# initializing list
test_list = [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
# printing original list
print("The original list is : " + str(test_list))
# Convert Character Matrix to single String
# Using join() + list comprehension
res = ''.join(ele for sub in test_list for ele in sub)
# printing result
print("The String after join : " + res)
输出 :
The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
The String after join : gfgisbest
方法 #2:使用join() + chain()
上述功能的组合可用于执行此任务。在此,我们通过 chain() 执行列表理解所执行的任务。
# Python3 code to demonstrate working of
# Convert Character Matrix to single String
# Using join() + chain()
from itertools import chain
# initializing list
test_list = [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
# printing original list
print("The original list is : " + str(test_list))
# Convert Character Matrix to single String
# Using join() + chain()
res = "".join(chain(*test_list))
# printing result
print("The String after join : " + res)
输出 :
The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
The String after join : gfgisbest