📜  Python – 从列表值中提取前面的记录

📅  最后修改于: 2022-05-13 01:54:24.259000             🧑  作者: Mango

Python – 从列表值中提取前面的记录

有时,在使用元组记录时,我们可能会遇到需要提取记录的问题,该记录位于提供的特定键之前。这类问题可以应用在 Web 开发和日常编程等领域。让我们讨论可以执行此任务的某些方式。

方法 #1:使用 zip() + enumerate() + 循环
上述功能的组合可用于执行此特定任务。在此,我们创建 2 个列表,一个从下一个索引开始。 zip() 有助于连接它们并使用 enumerate() 返回所需的结果以提取索引。

Python3
# Python3 code to demonstrate working of
# Extract Preceding Record
# Using zip() + enumerate() + loop
 
# initializing list
test_list = [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing Key
key = 'for'
 
# Extract Preceding Record
# Using zip() + enumerate() + loop
for idx, (a, b) in enumerate(zip(test_list, test_list[1:])):
    if b[0] == key:
        res = (a[0], a[1])
 
# printing result
print("The Preceding record : " + str(res))


Python3
# Python3 code to demonstrate working of
# Extract Preceding Record
# Using list comprehension + enumerate()
 
# initializing list
test_list = [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing Key
key = 'for'
 
# Extract Preceding Record
# Using list comprehension + enumerate()
res = [(test_list[idx - 1][0], test_list[idx - 1][1])
      for idx, (x, y) in enumerate(test_list) if x == key and idx > 0]
 
# printing result
print("The Preceding record : " + str(res))


输出
The original list is : [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
The Preceding record : ('best', 1)

方法 #2:使用列表理解 + enumerate()
上述功能的组合可以用来解决这个问题。在此,我们执行提取前一个元素以手动测试前一个键的任务,而不是像以前的方法那样创建一个单独的列表。

Python3

# Python3 code to demonstrate working of
# Extract Preceding Record
# Using list comprehension + enumerate()
 
# initializing list
test_list = [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing Key
key = 'for'
 
# Extract Preceding Record
# Using list comprehension + enumerate()
res = [(test_list[idx - 1][0], test_list[idx - 1][1])
      for idx, (x, y) in enumerate(test_list) if x == key and idx > 0]
 
# printing result
print("The Preceding record : " + str(res))
输出
The original list is : [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
The Preceding record : [('best', 1)]