📌  相关文章
📜  Python - 来自 K 值的下 N 个元素

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

Python - 来自 K 值的下 N 个元素

给定一个 List,从 List 中 K 值的出现处获取接下来的 N 个值。

方法#1:使用列表理解+切片

在这里,我们使用列表理解提取所有索引,然后使用循环来附加元素并从列表中所需的 K 值出现作为单个字符串加入。

Python3
# Python3 code to demonstrate working of
# Next N elements of K value
# Using list comprehension + slicing
  
# initializing list
test_list = [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 4
  
# initializing N
N = 2
  
# getting indices of K
temp = [idx for idx in range(len(test_list)) if test_list[idx] == K]
  
# getting next N elements from K using loop
res = []
for ele in temp:
  
    # appending slice
    res.extend(test_list[ele + 1: ele + N + 1])
  
# printing result
print("Constructed Result List : " + str(res))


Python3
# Python3 code to demonstrate working of
# Next N elements of K value
# Using filter() + lambda + loop
  
# initializing list
test_list = [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 4
  
# initializing N
N = 2
  
# getting indices of K
# using filter() and lambda
temp = list(filter(lambda ele: test_list[ele] == K, range(len(test_list))))
  
# getting next N elements from K using loop
res = []
for ele in temp:
  
    # appending slice
    res.extend(test_list[ele + 1: ele + N + 1])
  
# printing result
print("Constructed Result List : " + str(res))


输出
The original list is : [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9]
Constructed Result List : [6, 7, 7, 2, 2, 3]

方法 #2:使用 filter() + lambda + 循环

这与上述方法类似,不同之处在于使用 filter() 和 lambda 函数执行索引过滤。

蟒蛇3

# Python3 code to demonstrate working of
# Next N elements of K value
# Using filter() + lambda + loop
  
# initializing list
test_list = [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 4
  
# initializing N
N = 2
  
# getting indices of K
# using filter() and lambda
temp = list(filter(lambda ele: test_list[ele] == K, range(len(test_list))))
  
# getting next N elements from K using loop
res = []
for ele in temp:
  
    # appending slice
    res.extend(test_list[ele + 1: ele + N + 1])
  
# printing result
print("Constructed Result List : " + str(res))
输出
The original list is : [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9]
Constructed Result List : [6, 7, 7, 2, 2, 3]