Python – 将列表列表转换为元组的元组
有时,在处理Python数据时,我们可能会遇到需要执行数据类型相互转换的问题。这种问题可能发生在我们需要以特定格式获取数据的领域,例如机器学习。让我们讨论可以执行此任务的某些方式。
Input : test_list = [[‘Best’], [‘Gfg’], [‘Gfg’]]
Output : ((‘Best’, ), (‘Gfg’, ), (‘Gfg’, ))
Input : test_list = [[‘Gfg’, ‘is’, ‘Best’]]
Output : ((‘Gfg’, ‘is’, ‘Best’), )
方法 #1:使用tuple()
+ 列表推导
上述功能的组合可以用来解决这个问题。在此,我们使用 tuple() 执行转换,并使用列表推导将逻辑扩展到所有容器。
# Python3 code to demonstrate working of
# Convert List of Lists to Tuple of Tuples
# Using tuple + list comprehension
# initializing list
test_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],
['Gfg', 'is', 'for', 'Geeks']]
# printing original list
print("The original list is : " + str(test_list))
# Convert List of Lists to Tuple of Tuples
# Using tuple + list comprehension
res = tuple(tuple(sub) for sub in test_list)
# printing result
print("The converted data : " + str(res))
The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Gfg’, ‘is’, ‘love’], [‘Gfg’, ‘is’, ‘for’, ‘Geeks’]]
The converted data : ((‘Gfg’, ‘is’, ‘Best’), (‘Gfg’, ‘is’, ‘love’), (‘Gfg’, ‘is’, ‘for’, ‘Geeks’))
方法 #2:使用map() + tuple()
上述功能的组合可以用来解决这个问题。在此,我们使用 map() 执行使用列表推导执行的任务,以将转换逻辑扩展到每个子列表。
# Python3 code to demonstrate working of
# Convert List of Lists to Tuple of Tuples
# Using map() + tuple()
# initializing list
test_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],
['Gfg', 'is', 'for', 'Geeks']]
# printing original list
print("The original list is : " + str(test_list))
# Convert List of Lists to Tuple of Tuples
# Using map() + tuple()
res = tuple(map(tuple, test_list))
# printing result
print("The converted data : " + str(res))
The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Gfg’, ‘is’, ‘love’], [‘Gfg’, ‘is’, ‘for’, ‘Geeks’]]
The converted data : ((‘Gfg’, ‘is’, ‘Best’), (‘Gfg’, ‘is’, ‘love’), (‘Gfg’, ‘is’, ‘for’, ‘Geeks’))