Python|连接列表中的元组元素
如今,数据是任何机器学习技术的支柱。数据可以以任何形式出现,有时需要提取出来进行处理。本文处理提取列表中元组中存在的信息的问题。让我们讨论可以执行此操作的某些方式。
方法 #1:使用join() + list comprehension
join函数可用于将每个元组元素相互连接,列表理解处理遍历元组的任务。
# Python3 code to demonstrate
# joining tuple elements
# using join() + list comprehension
# initializing tuple list
test_list = [('geeks', 'for', 'geeks'),
('computer', 'science', 'portal')]
# printing original list
print ("The original list is : " + str(test_list))
# using join() + list comprehension
# joining tuple elements
res = [' '.join(tups) for tups in test_list]
# printing result
print ("The joined data is : " + str(res))
输出:
The original list is : [(‘geeks’, ‘for’, ‘geeks’), (‘computer’, ‘science’, ‘portal’)]
The joined data is : [‘geeks for geeks’, ‘computer science portal’]
输出 :
方法 #2:使用map() + join()
上述方法中列表推导的功能也可以使用 map函数来完成。这减少了代码的大小,增加了它的可读性。
# Python3 code to demonstrate
# joining tuple elements
# using join() + map()
# initializing tuple list
test_list = [('geeks', 'for', 'geeks'),
('computer', 'science', 'portal')]
# printing original list
print ("The original list is : " + str(test_list))
# using join() + map()
# joining tuple elements
res = list(map(" ".join, test_list))
# printing result
print ("The joined data is : " + str(res))
输出:
The original list is : [(‘geeks’, ‘for’, ‘geeks’), (‘computer’, ‘science’, ‘portal’)]
The joined data is : [‘geeks for geeks’, ‘computer science portal’]