Python - 如果相似的初始元素加入元组
有时,在使用Python元组时,我们可能会遇到需要根据初始元素的相似性执行记录连接的问题。这个问题可以在数据科学等数据领域有应用。让我们讨论可以执行此任务的某些方式。
Input : test_list = [(5, 6), (5, 7), (5, 8), (6, 10), (7, 13)]
Output : [(5, 6, 7, 8), (6, 10), (7, 13)]
Input : test_list = [(5, 6), (6, 7), (6, 8), (6, 10), (7, 13)]
Output : [(5, 6), (6, 7, 8, 10), (7, 13)]
方法#1:使用循环
这是可以完成此任务的粗暴方式。在此,如果我们之前没有发现类似的元组值出现,我们将创建新的元组。切片用于将其余元素添加到创建的元组中。
# Python3 code to demonstrate working of
# Join Tuples if similar initial element
# Using loop
# initializing list
test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
# printing original list
print("The original list is : " + str(test_list))
# Join Tuples if similar initial element
# Using loop
res = []
for sub in test_list:
if res and res[-1][0] == sub[0]:
res[-1].extend(sub[1:])
else:
res.append([ele for ele in sub])
res = list(map(tuple, res))
# printing result
print("The extracted elements : " + str(res))
输出 :
The original list is : [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
The extracted elements : [(5, 6, 7), (6, 8, 10), (7, 13)]
方法 #2:使用defaultdict()
+ 循环
上述功能的组合可以用来解决这个问题。它从上述方法中提供的优点是,它减少了初始化新密钥的检查,并且即使相似元素不连续也能很好地工作。
# Python3 code to demonstrate working of
# Join Tuples if similar initial element
# Using defaultdict() + loop
from collections import defaultdict
# initializing list
test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
# printing original list
print("The original list is : " + str(test_list))
# Join Tuples if similar initial element
# Using defaultdict() + loop
mapp = defaultdict(list)
for key, val in test_list:
mapp[key].append(val)
res = [(key, *val) for key, val in mapp.items()]
# printing result
print("The extracted elements : " + str(res))
输出 :
The original list is : [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
The extracted elements : [(5, 6, 7), (6, 8, 10), (7, 13)]