Python|将积分列表转换为元组列表
有时,在处理数据时,我们可能会遇到需要执行数据类型相互转换的问题。可能存在我们可能需要将整数列表元素转换为单元素元组的问题。让我们讨论可以执行此任务的某些方式。
方法#1:使用列表推导
列表推导可以用作解决此特定问题的速记方法。在此,我们遍历列表并将每个整数元素转换为元组对象。
# Python3 code to demonstrate working of
# Convert Integral list to tuple list
# using list comprehension
# initialize list
test_list = [1, 4, 6, 8, 9]
# printing original list
print("The original list : " + str(test_list))
# Convert Integral list to tuple list
# using list comprehension
res = [(ele, ) for ele in test_list]
# printing result
print("List after conversion to tuple list : " + str(res))
输出 :
The original list : [1, 4, 6, 8, 9]
List after conversion to tuple list : [(1, ), (4, ), (6, ), (8, ), (9, )]
方法 #2:使用zip() + list()
这是执行此特定任务的最简单方法。 zip()
当应用于整数列表时,它将每个元素转换为元组。它返回一个 zip 对象,因此它必须使用list()
转换回列表。
# Python3 code to demonstrate working of
# Convert Integral list to tuple list
# using zip() + list()
# initialize list
test_list = [1, 4, 6, 8, 9]
# printing original list
print("The original list : " + str(test_list))
# Convert Integral list to tuple list
# using zip() + list()
res = list(zip(test_list))
# printing result
print("List after conversion to tuple list : " + str(res))
输出 :
The original list : [1, 4, 6, 8, 9]
List after conversion to tuple list : [(1, ), (4, ), (6, ), (8, ), (9, )]