Python - 在元组列表中按秒查找第一个元素
有时,在处理Python记录时,我们可能会遇到需要从给定的第二个元素中找到元组的第一个元素的问题。此类问题可能发生在 Web 开发等领域。让我们讨论可以执行此任务的某些方式。
Input :
test_list = [(4, 5), (5, 6), (1, 3), (6, 6)]
K = 6
Output : [5, 6]
Input :
test_list = [(4, 5), (5, 7), (1, 3), (6, 8)]
K = 6
Output : []
方法#1:使用列表理解
这是可以执行此任务的方式之一。在此,我们对每个元组进行迭代,如果我们找到与值匹配的键,我们将存储在结果列表中。
Python3
# Python3 code to demonstrate working of
# Find first element by second in tuple List
# Using list comprehension
# initializing list
test_list = [(4, 5), (5, 6), (1, 3), (6, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 6
# Find first element by second in tuple List
# Using list comprehension
res = [x for (x, y) in test_list if y == K]
# printing result
print("The key from value : " + str(res))
Python3
# Python3 code to demonstrate working of
# Find first element by second in tuple List
# Using next() + generator expression
# initializing list
test_list = [(4, 5), (5, 6), (1, 3), (6, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 6
# Find first element by second in tuple List
# Using next() + generator expression
res = next((x for x, y in test_list if y == K), None)
# printing result
print("The key from value : " + str(res))
输出 :
The original list is : [(4, 5), (5, 6), (1, 3), (6, 9)]
The key from value : [5]
方法 #2:使用next()
+ 生成器表达式
这是可以解决此任务的另一种方式。在这里,next() 用于获取连续元素,生成器表达式用于检查逻辑。
Python3
# Python3 code to demonstrate working of
# Find first element by second in tuple List
# Using next() + generator expression
# initializing list
test_list = [(4, 5), (5, 6), (1, 3), (6, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 6
# Find first element by second in tuple List
# Using next() + generator expression
res = next((x for x, y in test_list if y == K), None)
# printing result
print("The key from value : " + str(res))
输出 :
The original list is : [(4, 5), (5, 6), (1, 3), (6, 9)]
The key from value : 5