📜  Python - 从 K 成功的列表中提取元素

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

Python - 从 K 成功的列表中提取元素

给定一个列表,提取将 K 作为下一个元素的元素。

方法#1:使用循环

在这里,我们迭代列表并查找每个 K,并提取它前面的元素。

Python3
# Python3 code to demonstrate working of
# Extract elements succeeded by K
# Using loop
  
# initializing list
test_list = [2, 3, 5, 7, 8, 5, 3, 5]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
# Using loop to extract elements succeeded by K
res = []
for idx in range(len(test_list) - 1):
  
    # checking for succession
    if test_list[idx + 1] == K:
        res.append(test_list[idx])
  
# printing result
print("Extracted elements list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Extract elements succeeded by K
# Using list comprehension
  
# initializing list
test_list = [2, 3, 5, 7, 8, 5, 3, 5]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
# List comprehension used as shorthand
res = [test_list[idx]
       for idx in range(len(test_list) - 1) if test_list[idx + 1] == K]
  
# printing result
print("Extracted elements list : " + str(res))


输出
The original list is : [2, 3, 5, 7, 8, 5, 3, 5]
Extracted elements list : [3, 8, 3]

方法#2:使用列表理解

解决这个问题的另一种方式,在这里,我们使用列表理解作为速记来解决获取元素的问题。

蟒蛇3

# Python3 code to demonstrate working of
# Extract elements succeeded by K
# Using list comprehension
  
# initializing list
test_list = [2, 3, 5, 7, 8, 5, 3, 5]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
# List comprehension used as shorthand
res = [test_list[idx]
       for idx in range(len(test_list) - 1) if test_list[idx + 1] == K]
  
# printing result
print("Extracted elements list : " + str(res))
输出
The original list is : [2, 3, 5, 7, 8, 5, 3, 5]
Extracted elements list : [3, 8, 3]