Python – 唯一的第 K 个定位元组
有时,在处理Python记录时,我们可能会遇到一个问题,即我们只需要根据一些特定的元组索引来提取唯一的元组。这类问题可以在 Web 开发等领域有应用。让我们讨论可以执行此任务的某些方式。
Input :
test_list = [(5, 6, 5), (4, 2, 7), (1, 2, 3), (9, 6, 5)]
K = 3
Output : [(1, 2, 3), (5, 6, 5), (4, 2, 7)]
Input :
test_list = [(5, ), (1, ), (1, ), (9, )]
K = 1
Output : [(1, ), (5, ), (9, )]
方法 #1:使用map() + next()
+ lambda
上述功能的组合可以用来解决这个问题。在此,我们扩展了使用 lambda函数和 next() 提取唯一元素的逻辑,使用 map()。
# Python3 code to demonstrate working of
# Unique Kth index tuples
# Using map() + next() + lambda
# initializing list
test_list = [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# Unique Kth index tuples
# Using map() + next() + lambda
res = [*map(lambda ele: next(tup for tup in test_list if tup[K - 1] == ele),
{tup[K - 1] for tup in test_list})]
# printing result
print("The extracted elements : " + str(res))
输出 :
The original list is : [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)]
The extracted elements : [(4, 2, 7), (5, 6, 8)]
方法 #2:使用next() + groupby() + lambda
上述功能的组合也可以用来解决这个问题。在此,我们使用 groupby() 以更紧凑的方式执行上面的 map() 任务。
# Python3 code to demonstrate working of
# Unique Kth index tuples
# Using next() + groupby() + lambda
from itertools import groupby
# initializing list
test_list = [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# Unique Kth index tuples
# Using next() + groupby() + lambda
temp = lambda ele : ele[K - 1]
res = [next(val) for _, val in groupby(sorted(test_list, key = temp), key = temp)]
# printing result
print("The extracted elements : " + str(res))
输出 :
The original list is : [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)]
The extracted elements : [(4, 2, 7), (5, 6, 8)]