Python| Zip 不均匀元组
在Python中,压缩是一种实用程序,我们将一条记录与另一条记录配对。通常,只有在要压缩的两条记录的大小相同的情况下,此任务才会成功。但有时我们需要压缩不同大小的记录。让我们讨论如果发生此问题可以解决的某些方法。
方法 #1:使用enumerate()
+ 循环
这就是我们使用蛮力方法来完成这个特定任务的方式。在这个过程中,我们循环两个元组,当一个元组变得比另一个大时,我们循环元素以从头开始它们。
# Python3 code to demonstrate
# Zip Uneven Tuple
# using enumerate() + loop
# initializing tuples
test_tup1 = (7, 8, 4, 5, 9, 10)
test_tup2 = (1, 5, 6)
# printing original tuples
print ("The original tuple 1 is : " + str(test_tup1))
print ("The original tuple 2 is : " + str(test_tup2))
# using enumerate() + loop
# Zip Uneven Tuple
res = []
for i, j in enumerate(test_tup1):
res.append((j, test_tup2[i % len(test_tup2)]))
# printing result
print ("The zipped tuple is : " + str(res))
输出 :
The original tuple 1 is : (7, 8, 4, 5, 9, 10)
The original tuple 2 is : (1, 5, 6)
The zipped tuple is : [(7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6)]
方法#2:使用itertools.cycle()
这是执行此特定任务的另一种方法,在此我们循环较小的元组,以便它可以从头开始压缩,以防使用 zip函数耗尽较小的元组。
# Python3 code to demonstrate
# Zip Uneven Tuple
# using itertools.cycle()
from itertools import cycle
# initializing tuples
test_tup1 = (7, 8, 4, 5, 9, 10)
test_tup2 = (1, 5, 6)
# printing original tuples
print ("The original tuple 1 is : " + str(test_tup1))
print ("The original tuple 2 is : " + str(test_tup2))
# using itertools.cycle()
# Zip Uneven Tuple
res = list(zip(test_tup1, cycle(test_tup2)) if len(test_tup1) > len(test_tup2) else zip(cycle(test_tup1), test_tup2))
# printing result
print ("The zipped tuple is : " + str(res))
输出 :
The original tuple 1 is : (7, 8, 4, 5, 9, 10)
The original tuple 2 is : (1, 5, 6)
The zipped tuple is : [(7, 1), (8, 5), (4, 6), (5, 1), (9, 5), (10, 6)]