Python|将元组列表转换为字符串列表
数据类型之间的相互转换是非常有用的实用程序,并且已经编写了许多文章来执行相同的操作。本文讨论字符元组到单个字符串之间的相互转换。这种相互转换在机器学习中很有用,在机器学习中,我们需要以特定格式提供输入来训练模型。让我们讨论一些可以做到这一点的方法。
方法 #1:使用列表理解 + join()
列表推导执行迭代整个元组列表的任务,而连接函数执行将元组的元素聚合到一个列表中的任务。
# Python3 code to demonstrate
# conversion of list of tuple to list of list
# using list comprehension + join()
# initializing list
test_list = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'),
('G', 'E', 'E', 'K', 'S')]
# printing the original list
print ("The original list is : " + str(test_list))
# using list comprehension + join()
# conversion of list of tuple to list of list
res = [''.join(i) for i in test_list]
# printing result
print ("The list after conversion to list of string : " + str(res))
输出 :
The original list is : [(‘G’, ‘E’, ‘E’, ‘K’, ‘S’), (‘F’, ‘O’, ‘R’), (‘G’, ‘E’, ‘E’, ‘K’, ‘S’)]
The list after conversion to list of string : [‘GEEKS’, ‘FOR’, ‘GEEKS’]
方法 #2:使用map() + join()
列表推导式执行的任务可以由 map函数执行,该函数可以将一个元组的逻辑扩展到列表中的所有元组。
# Python3 code to demonstrate
# conversion of list of tuple to list of list
# using map() + join()
# initializing list
test_list = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'),
('G', 'E', 'E', 'K', 'S')]
# printing the original list
print ("The original list is : " + str(test_list))
# using map() + join()
# conversion of list of tuple to list of list
res = list(map(''.join, test_list))
# printing result
print ("The list after conversion to list of string : " + str(res))
输出 :
The original list is : [(‘G’, ‘E’, ‘E’, ‘K’, ‘S’), (‘F’, ‘O’, ‘R’), (‘G’, ‘E’, ‘E’, ‘K’, ‘S’)]
The list after conversion to list of string : [‘GEEKS’, ‘FOR’, ‘GEEKS’]