Python – 从值列表中检测元组键
有时,在处理记录数据时,我们可能会遇到需要从其值列表中提取具有匹配值 K 的键的问题。此类问题可能发生在与数据链接的域中。让我们讨论可以执行此任务的某些方式。
方法#1:使用列表推导
可以使用列表推导来执行此任务。在此,我们遍历每条记录并测试它的 K 值列表。如果找到,我们返回该键。
Python3
# Python3 code to demonstrate
# Tuple key detection from value list
# using List comprehension
# Initializing list
test_list = [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 4
# Tuple key detection from value list
# using List comprehension
res = [sub[0] for sub in test_list if K in sub[1]]
# printing result
print ("The required key of list values : " + str(res))
Python3
# Python3 code to demonstrate
# Tuple key detection from value list
# using filter() + lambda
# Initializing list
test_list = [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 4
# Tuple key detection from value list
# using filter() + lambda
res = list(filter(lambda sub, ele = K : ele in sub[1], test_list))
# printing result
print ("The required key of list values : " + str(res[0][0]))
输出 :
The original list is : [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
The required key of list values : ['Gfg']
方法 #2:使用 filter() + lambda
上述功能的组合也可用于执行此任务。在此,filter() 用于检查列表中是否存在并在 lambda 的帮助下提取所需的键。
Python3
# Python3 code to demonstrate
# Tuple key detection from value list
# using filter() + lambda
# Initializing list
test_list = [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 4
# Tuple key detection from value list
# using filter() + lambda
res = list(filter(lambda sub, ele = K : ele in sub[1], test_list))
# printing result
print ("The required key of list values : " + str(res[0][0]))
输出 :
The original list is : [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
The required key of list values : Gfg