Python – 将元组加入元组列表中的整数
有时,在处理Python记录时,我们可能会遇到一个问题,即我们需要连接所有元素,以便将 List 中的元组中的元素转换为整数。这种问题可以在许多领域都有应用,例如日间和竞争性编程。让我们讨论可以执行此任务的某些方式。
Input : test_list = [(4, 5, 6), (5, 1), (1, 3, 8, 0), (6, 9)]
Output : [456, 51, 1380, 69]
Input : test_list = [(4, 5, 6, 8, 9)]
Output : [45689]
方法#1:使用循环
这是可以执行此任务的蛮力方法。在此,我们使用数字创建来执行所有元素的连接,以数学方式计算结果。
# Python3 code to demonstrate working of
# Join Tuples to Integers in Tuple List
# Using loop
# helpr_fnc
def join_tup(tup):
res = tup[0]
for idx in tup[1:]:
res = res * 10 + idx
return res
# initializing list
test_list = [(4, 5), (5, 6), (1, 3), (6, 9)]
# printing original list
print("The original list is : " + str(test_list))
# Join Tuples to Integers in Tuple List
# Using loop
res = [join_tup(idx) for idx in test_list]
# printing result
print("The joined result : " + str(res))
输出 :
The original list is : [(4, 5), (5, 6), (1, 3), (6, 9)]
The joined result : [45, 56, 13, 69]
方法 #2:使用map() + join() + int()
上述功能的组合可以用来解决这个问题。在此,我们通过字符串转换执行连接,使用 join() 和 int() 连接用于将结果转换回整数。
# Python3 code to demonstrate working of
# Join Tuples to Integers in Tuple List
# Using map() + join() + int()
# initializing list
test_list = [(4, 5), (5, 6), (1, 3), (6, 9)]
# printing original list
print("The original list is : " + str(test_list))
# Join Tuples to Integers in Tuple List
# Using map() + join() + int()
res = [int(''.join(map(str, idx))) for idx in test_list]
# printing result
print("The joined result : " + str(res))
输出 :
The original list is : [(4, 5), (5, 6), (1, 3), (6, 9)]
The joined result : [45, 56, 13, 69]