Python|二进制组元组列表元素
有时,在处理元组时,我们可能会遇到分组问题,无论是基于性别还是任何特定的二元类别。这可以在许多领域有应用。让我们讨论可以执行此操作的某些方式。
方法 #1:使用生成器 + 循环 + zip()
执行此任务的蛮力方法,在此,我们在zip()
的帮助下执行组合分组,迭代逻辑由生成器和循环处理。
# Python3 code to demonstrate working of
# Binary Group Tuple list elements
# using generator + loop + zip()
# helper function to perform task
def bin_group(test_list):
for tup1, tup2 in zip(test_list[0::2], test_list[1::2]):
yield (tup1[0], tup1[1], tup2[1])
# initialize list
test_list = [(1, 56, 'M'), (1, 14, 'F'), (2, 43, 'F'), (2, 10, 'M')]
# printing original list
print("The original list : " + str(test_list))
# Binary Group Tuple list elements
# using generator + loop + zip()
res = list(bin_group(test_list))
# printing result
print("The list after binary grouping : " + str(res))
输出 :
The original list : [(1, 56, 'M'), (1, 14, 'F'), (2, 43, 'F'), (2, 10, 'M')]
The list after binary grouping : [(1, 56, 14), (2, 43, 10)]
方法 #2:使用 defaultdict() + 列表理解 + sorted() + items()
上述功能的组合可用于执行此任务。在此,我们将列表转换为字典,然后执行基于键的分组并重新排列回元组列表。
# Python3 code to demonstrate working of
# Binary Group Tuple list elements
# using defaultdict() + list comprehension + sorted() + items()
from collections import defaultdict
# initialize list
test_list = [(1, 56, 'M'), (1, 14, 'F'), (2, 43, 'F'), (2, 10, 'M')]
# printing original list
print("The original list : " + str(test_list))
# Binary Group Tuple list elements
# using defaultdict() + list comprehension + sorted() + items()
temp = defaultdict(list)
for ele in test_list:
temp[ele[0]].append(ele[1])
res = sorted((key, ) + tuple(val) for key, val in temp.items())
# printing result
print("The list after binary grouping : " + str(res))
输出 :
The original list : [(1, 56, 'M'), (1, 14, 'F'), (2, 43, 'F'), (2, 10, 'M')]
The list after binary grouping : [(1, 56, 14), (2, 43, 10)]